
function Search(){
	this.data={
		_regime:'simple',
		precise:0,
		type:ROUTE_TYPE_PASSENGER,
		precise_1_hours_grades:[1,2,3,6,12,24],
		precise_2_days_grades:[1,2,3,7,30],
		exportFields:{
			'simple':[
				'from_city',
				'to_city',
				'from_date',
				'type',
				'with_info'
				],
			'advanced':[
				'from_city',
				'from_street',
				'from_house',
				'from_subway',
				'to_city',
				'to_street',
				'to_house',
				'to_subway',
				'from_date',
				'from_time',
				'precise',
				'precise_1_hours',
				'precise_2_days',
				'type',
				'with_info'
				]
			},
		_page:1,
		_perpage:10,
		_offset:0,
		_pagerWing:5,
		_searchResultFormat:'html'
		}
	}


Search.prototype.initialize=function(property){
	if (property){
		return this.data[property];
		}
	else{
		return this.data;
		}
	}
Search.prototype.appendType=function(){
	var
		container=this.getData('container'),
		type=this.getData('type');
	toggleClass(container,(type==ROUTE_TYPE_PASSENGER?1:0),['type_'+ROUTE_TYPE_DRIVER,'type_'+ROUTE_TYPE_PASSENGER]);
	$checked('type_'+type,true);
	return true;
	}

Search.prototype.render=function(){
	var m;

	this.refreshData();
	$clear(this.getData('container'));

	if (method_exists(this,m='render_'+this.getData('_regime'))){
		return (this[m]() && this.appendType());
		}
	return false;
	}

Search.prototype.refreshData=function(){
	if ($id('from_time')){
		this.setData('from_time',$id('from_time').value);
		}
	if ($id('precise_0')){
		this.setData('precise',getRadioValue('precise'));

		if ($id('precise_1_hours')){
			this.setData('precise_1_hours',$disabled('precise_1_hours')?null:$id('precise_1_hours').value);
			}
		if ($id('precise_2_days')){
			this.setData('precise_2_days',$disabled('precise_2_days')?null:$id('precise_2_days').value);
			}
		}
	if (this.getData('from_city_hasStreet') && $id('from_house')){
		this.setData('from_house',$value('from_house'));
		}
	if (this.getData('to_city_hasStreet') && $id('to_house')){
		this.setData('to_house',$value('to_house'));
		}
	if ($id('with_info')){
		this.setData('with_info', +$checked('with_info'));	
		}

	}

Search.prototype.render_simple=function(){
	var
		$this=this,
		container=this.getData('container'),
		searchForm=setChildExt(
			{
				parent:container,
				tag:'FORM',
				params:{
					method:'get',
					action:'/search/'
					},
				children:[
					$this.getSwitchTypeNodes(),
					{
						tag:'DL',
						children:[
							{
								tag:'DD',
								className:'col-1',
								child:{
									tag:'H3',
									content:'Откуда'
									}
								},
							{
								tag:'DD',
								className:'col-2',
								child:{
									tag:'H3',
									content:'Куда'
									}
								}
							]
						},
					{
						tag:'DL',
						className:'highlighted',
						children:[
							{
								tag:'DD',
								className:'col-1',
								children:this.getPointNodes('from')
								},
							{
								tag:'DD',
								className:'col-2',
								children:this.getPointNodes('to',{city:true, with_info:true})
								},
							{
								tag:'DD',
								className:'clear'
								}
							]
						},
					{
						id:'search-type-switcher',
						child:{
							tag:'SPAN',
							className:'simple-search',
							child:{
								tag:'A',
								className:'js-link',
								onclick:function(){
									$this.setData('_regime','advanced');
									return $this.render();
									},
								content:'Расширенный поиск'
								}
							}
						},
					{
						className:'submit centered distant',
						child:{
							className:'button wide41',
							content:'<button type="submit" onfocus="blur()"><span>Найти</span></button>'
							/* child:{
								tag:'BUTTON',
								onfocus:selfBlur,
								onclick:function(){
									searchForm.submit();
									return false;
									},
								child:{
									tag:'SPAN',
									content:'Найти'
									}
								} */
							}
						}
					]
				}
			);
		this.appendForm(searchForm);
	return true;
	}

Search.prototype.appendForm=function(form){
	if (!form){
		return false;
		}
	var $this=this;
	var dif=new DOCUMENT_IFORM(
		{
			form:form,
			fields:{
				from_city:$this.getCitySuggestFieldParams('from'),
				from_street:$this.getStreetSuggestFieldParams('from'),
				from_house:'house',
				from_subway:$this.getSubwaySuggestFieldParams('from'),
				to_city:$this.getCitySuggestFieldParams('to'),
				to_street:$this.getStreetSuggestFieldParams('to'),
				to_house:'house',
				to_subway:$this.getSubwaySuggestFieldParams('to'),
				from_date:{
					f_template:'date_calendar',
					f_resSource:'value_dt',
					f_onselect:function(dt){
						$this.setData('from_date',dt);
						}
					},
				from_time:{
					f_type:'select'
					},
				precise:{
					f_type:'radioGroup'
					},
				precise_1_hours:{
					f_type:'select'
					},
				precise_2_days:{
					f_type:'select'
					}
				},
			onresult:function(res){
				$this.search();
				return false;
				}
			}
		);
	}

Search.prototype.search=function(){
	//this.render();
	results=this.exportData();
	this.doSearch(results);
	}

/* Returns main form results */
Search.prototype.exportData=function(prefix){
	this.refreshData();
	var
		res={},
		exportFields=(this.getData('exportFields'))[this.getData('_regime')],
		fullData=this.getData();

	for (var field in fullData){
		if (!in_array(exportFields,field) || is_null(fullData[field])){
			continue;
			}
		var val=fullData[field];
		if (is_date(val)){
			res[field]=val.toDT();
			}
		else{
			res[field]=val;
			}
		}

	return res;
	}

/* Get search results from server */
Search.prototype.doSearch=function(params){
	if (!is_object(params)){
		return false;
		}
	var $this=this;
	makeAjaxExt(
		{
			params:
				concatObjects(
					{
						todo:'searchRoutes',
						page:$this.getData('_page'),
						perpage:$this.getData('_perpage'),
						_searchResultFormat:$this.getData('_searchResultFormat')
						},
					params
					),
			bs:true,
			onload:function(res){
				$this.displayResults(res);
				var hash=concatObjects(
					params,
					{
						page:res.page
						}
					);
				TriDorogiPage.setHash(hash);
				}
			}
		);
	}


Search.prototype.displayResults=function(res){
	var
		$this=this,
		formContainer=this.getData('container'),
		wrapContainer=this.getData('wrapContainer'),
		resContainer=
			$id('search-results')
			||
			setChildExt(
				{
					parent:wrapContainer,
					id:'search-results'
					}
				);
	toggleClass(formContainer,0);
	this.render();
	$clear(resContainer);
	setChildExt(
		{
			parent:resContainer,
			className:'given-params',
			children:[
				{
					tag:'A',
					id:'toggleSearchContainerLink',
					params:{
						href:'#'
						},
					content:'Изменить параметры поиска',
					onclick:function(){
						$this.toggleSearchContainer();
						return false;
						}
					},
				{
					tag:'SPAN',
					content:':&nbsp;'
					},
				{
					child:this.getSearchParamStr()
					}
				]
			}
		);

	if (res.totalCount){
		var pagerSettings={
				page:res.page,
				perpage:res.perPage,
				total:res.totalCount,
				wing:this.getData('_pagerWing'),
				onclick:function(page){
					$this.setData('_page',page);
					$this.search();
					return;
					}
				};

		resContainer.appendChild(getPager(pagerSettings));
		}
	else{
		setChildExt(
			{
				parent:resContainer,
				children:[
					{
						children:[
							{
								tag:'STRONG',
								className:'accent',
								content:'Не найдено ни одного маршрута, соответствующего требованиям'
								},
							{
								children:[
									{
										tag:'SPAN',
										content:'Попробуйте '
										},
									{
										tag:'A',
										params:{
											href:'javascript:;'
											},
										onclick:function(){
											$this.toggleSearchContainer();
											return false;
											},
										content:'изменить параметры поиска'
										},
									{
										tag:'SPAN',
										content:'&nbsp;или <a href="'+PATH_ROUTES_NEW+'">создайте свой маршрут</a> с нужными параметрами, чтобы найти попутчиков.'
										}
									]
								}
							]
						}
					]
				}
			);
		}
	setChildExt(
		{
			parent:resContainer,
			content:res.html
			}
		);
	//$innerHTML(resContainer,html);
	return true;
	}

Search.prototype.toggleSearchContainer=function(){
	var container=this.getData('container');
	if (!container){
		return false;
		}
	/* if (!$displaying(container)){
		slideDown(
			container,
			{
				speed:50,
				oncomplete:function(){
					$innerHTML('toggleSearchContainerLink','Скрыть параметры поиска');
					}
				}
			);
		}
	else{
		$innerHTML('toggleSearchContainerLink','Скрыть параметры поиска');
		} */
	$innerHTML('toggleSearchContainerLink',toggleClass(container)?'Скрыть параметры поиска':'Изменить параметры поиска');
	return false;
	}
Search.prototype.getSearchParamStr=function(){
	var
		data=this.getData(),
		isLocal=(data.from_city==data.to_city),
		children=[];
	var append=function(content,className){
		children.push(
			{
				tag:'LI',
				content:content,
				className:className||''
				}
			);
		}
	append(data.type==ROUTE_TYPE_PASSENGER?'Я&nbsp;&mdash; пассажир, <strong>ищу водителей</strong>':'Я&nbsp;&mdash; водитель, <strong>ищу пассажиров</strong>');
	var
		fromToStr='',
		fromStr='',
		toStr='',
		getCityDetailsStr=function(prefix){
			var
				street=data[prefix+'_street_nameFull'],
				house=data[prefix+'_house'],
				subway=data[prefix+'_subway_nameFull'],
				parts=[];
			if (street){
				parts.push(street+(house?', д.&nbsp;'+house:''));
				}
			if (subway){
				parts.push('м.&nbsp;'+subway);
				}
			return parts.join(', ');
			};

	fromStr+=getCityDetailsStr('from');
	toStr+=getCityDetailsStr('to');
	if (isLocal){
		if (fromStr && toStr){
			fromToStr=fromStr+'&nbsp;&mdash; '+toStr;
			}
		else if (fromStr && !toStr){
			fromToStr='Отправление: '+ fromStr;
			}
		else if (!fromStr && toStr){
			fromToStr='Прибытие: '+ toStr;
			}
		if (fromStr || toStr){
			fromToStr+=' ('+data.from_city_nameFull+')'
			}
		else{
			fromToStr+=data.from_city_nameFull+' (внутренний маршрут)';
			}
		}
	else{
		fromToStr=''
			+ (
				data.from_city_nameFull
					? data.from_city_nameFull + (fromStr ? ' (' + fromStr + ')' : '')
					: 'Неизвестный пункт'
				)
			+ '&nbsp;&mdash; '
			+ (
				data.to_city_nameFull
					? data.to_city_nameFull + ( toStr ? ' (' + toStr + ')' : '')
					: 'Неизвестный пункт'
				)
		}
	append(fromToStr);
	if (data.from_date){
		var dtStr=is_date(data.from_date)?data.from_date.getReadable():data.from_date.dateStr();
		if (isset(data.from_time)){
			dtStr+=data.from_time!='0'?' в&nbsp;'+data.from_time:'';
			}
		if (isset(data.precise) && data._regime=='advanced'){
			switch(Number(data.precise)){
				case 0:
					dtStr+=' (строго)';
					break;
				case 1:
					dtStr+=' (±&nbsp;'+DATES.getEnging(data.precise_1_hours,'hours')+')';
					break;
				case 2:
					dtStr+=' (±&nbsp;'+DATES.getEnging(data.precise_2_days,'days')+')';
					break;
				}
			}
		append(dtStr);
		}

	var str={
			child:{
				tag:'UL',
				className:'type_'+data.type,
				children:children
				}
			};
	return str;
	}

/* Returns document_iform params for city field with suggest */
Search.prototype.getCitySuggestFieldParams=function(prefix){
	var $this=this;
	return {
		f_template:'city',
		f_min:0,
		f_callback: function(val){
			var 
				$field = $(this),
				validator = this.obj,
				$form = $(validator.form),
				type = $field.attr('id').toString('_').split('_').shift(),
				$otherField = $form.find('#' + (type == 'from' ? 'to' : 'from') + '_city');
			return !!(trimStr(val) || trimStr($otherField.val()));
			},
		f_suggest:{
			f_action:'getCities',
			value:this.getData(prefix+'_city_pseudoFieldValue'),
			minContainerWidth:200,
			f_onselect:function(data){
				var resetDependents=function(){
					$this.setData(prefix+'_street',null);
					$this.setData(prefix+'_street_nameFull',null);
					$this.setData(prefix+'_street_pseudoFieldValue',null);
					$this.setData(prefix+'_house',null);
					$clearValue(prefix+'_house');
					$this.setData(prefix+'_subway',null);
					$this.setData(prefix+'_subway_nameFull',null);
					$this.setData(prefix+'_subway_pseudoFieldValue',null);
					}
				if (!data || !data.id){
					resetDependents();
					$this.setData(prefix+'_city',null);
					$this.setData(prefix+'_city_nameFull',null);
					$this.setData(prefix+'_city_hasStreet',null);
					$this.setData(prefix+'_city_hasSubway',null);
					$this.setData(prefix+'_city_pseudoFieldValue','');
					return false;
					}
				var prevId=$this.getData(prefix+'_city');
				if (prevId && prevId!=data.id){
					resetDependents();
					}
				$this.setData(prefix+'_city',data.id);
				$this.setData(prefix+'_city_nameFull',data.name_full);
				$this.setData(prefix+'_city_hasStreet',!!Number(data.has_street));
				$this.setData(prefix+'_city_hasSubway',!!Number(data.has_subway));
				$this.setData(prefix+'_city_pseudoFieldValue',data._pseudoFieldValue);
				$this.render();
				if (prefix == 'from'){
					setTimeout(function(){
						try{
							$('#to_city')[0]._suggest.start();
							} catch (e){}
						}, 100);
					}
				else if (prefix == 'to'){
					$('#from_date').focus();
					}
				}
			}
		};
	}

/* Returns document_iform params for street field with suggest */
Search.prototype.getStreetSuggestFieldParams=function(prefix){
	var $this=this;
	return {
		f_template:'street',
		f_suggest:{
			f_action:'getStreets',
			value:this.getData(prefix+'_street_pseudoFieldValue'),
			f_prepare:function(){
				return {
					city:$this.getData(prefix+'_city')
					}
				},
			f_onselect:function(data){
				if (!data || !data.id){
					$this.setData(prefix+'_street',null);
					$this.setData(prefix+'_street_nameFull','');
					$this.setData(prefix+'_street_pseudoFieldValue','');
					return false;
					}
				$this.setData(prefix+'_street',data.id);
				$this.setData(prefix+'_street_nameFull',data.name_full);
				$this.setData(prefix+'_street_pseudoFieldValue',data._pseudoFieldValue);
				//$this.render();
				}
			}
		};
	}

/* Returns document_iform params for street field with suggest */
Search.prototype.getSubwaySuggestFieldParams=function(prefix){
	var $this=this;
	return {
		f_template:'subway',
		f_suggest:{
			f_action:'getSubways',
			value:this.getData(prefix+'_subway_pseudoFieldValue'),
			f_prepare:function(){
				return {
					city:$this.getData(prefix+'_city')
					}
				},
			f_onselect:function(data){
				if (!data || !data.id){
					$this.setData(prefix+'_subway',null);
					$this.setData(prefix+'_subway_nameFull','');
					$this.setData(prefix+'_subway_pseudoFieldValue','');
					return false;
					}
				$this.setData(prefix+'_subway',data.id);
				$this.setData(prefix+'_subway_nameFull',data.name_full);
				$this.setData(prefix+'_subway_pseudoFieldValue',data._pseudoFieldValue);
				//$this.render();
				}
			}
		};
	}

Search.prototype.render_advanced=function(){
	var
		$this=this,
		container=this.getData('container'),
		searchForm=setChildExt(
			{
				parent:container,
				tag:'FORM',
				params:{
					method:'get',
					action:'/search/'
					},
				children:[
					$this.getSwitchTypeNodes(),
					{
						tag:'DL',
						children:[
							{
								tag:'DD',
								className:'col-1',
								child:{
									tag:'H3',
									content:'Откуда'
									}
								},
							{
								tag:'DD',
								className:'col-2',
								child:{
									tag:'H3',
									content:'Куда'
									}
								}
							]
						},
					{
						tag:'DL',
						className:'highlighted',
						children:[
							{
								tag:'DD',
								className:'col-1',
								children:this.getPointNodes('from')
								},
							{
								tag:'DD',
								className:'col-2',
								children:this.getPointNodes('to')
								},
							{
								tag:'DD',
								className:'clear'
								}
							]
						},
					{
						tag:'DL',
						children:[
							{
								tag:'DD',
								className:'col-1',
								child:{
									tag:'H3',
									content:'Отправление'
									}
								},
							{
								tag:'DD',
								className:'col-2',
								child:{
									tag:'H3',
									content:'Точность'
									}
								}
							]
						},
					{
						tag:'DL',
						className:'highlighted halflighted',
						children:[
							{
								tag:'DD',
								className:'col-1',
								children:this.getPointNodes('from',{date:true,time:true})

								},
							{
								tag:'DD',
								className:'col-2',
								children:[
									{
										tag:'UL',
										className:'radio-list',
										id:'precise-list',
										children:[

											/* Strange IE bug hack */
											(

											 BROWSER.isIE?
												{
													tag:'LI',
													className:'hidden',
													children:[
														{
															tag:'INPUT',
															type:'radio',
															name:'precise',
															disabled:true
															}
														]
													}
												:''
												),
											/* / Strange IE bug hack */
											{
												tag:'LI',
												children:[
													{
														tag:'INPUT',
														type:'radio',
														name:'precise',
														id:'precise_0',
														checked:($this.getData('precise')==0),
														value:0,
														onclick:function(){$this.refreshPreciseSelectors()}
														},
													{
														tag:'LABEL',
														params:{
															htmlFor:'precise_0'
															},
														content:'Строгое соответствие дате и времени'
														}
													]
												},


											{
												tag:'LI',
												children:[
													{
														tag:'INPUT',
														type:'radio',
														name:'precise',
														id:'precise_1',
														checked:($this.getData('precise')==1),
														value:1,
														onclick:function(){$this.refreshPreciseSelectors()}
														},
													{
														tag:'LABEL',
														params:{
															htmlFor:'precise_1'
															},
														content:'Дата фиксирована, время может варьироваться на ± '
														},
													{
														tag:'SELECT',
														id:'precise_1_hours',
														name:'precise_1_hours',
														children:(
															function(){
																var
																	opts=$this.getData('precise_1_hours_grades'),
																	res=[],
																	selected=Number($this.getData('precise_1_hours'));
																for(var i=0;i<opts.length;i++){
																	res.push(
																		{
																			tag:'OPTION',
																			value:opts[i],
																			content:DATES.getEnging(opts[i],'hours'),
																			selected:(selected==opts[i])
																			}
																		);
																	}

																return res;
																}
															)()
														}
													]
												},
											{
												tag:'LI',
												children:[
													{
														tag:'INPUT',
														type:'radio',
														name:'precise',
														id:'precise_2',
														checked:($this.getData('precise')==2),
														value:2,
														onclick:function(){$this.refreshPreciseSelectors()}
														},
													{
														tag:'LABEL',
														params:{
															htmlFor:'precise_2'
															},
														content:'Дата может варьироваться на ± '
														},
													{
														tag:'SELECT',
														id:'precise_2_days',
														name:'precise_2_days',
														children:(
															function(){
																var
																	opts=$this.getData('precise_2_days_grades'),
																	res=[],
																	selected=$this.getData('precise_2_days');
																for(var i=0;i<opts.length;i++){
																	res.push(
																		{
																			tag:'OPTION',
																			value:opts[i],
																			content:DATES.getEnging(opts[i],'days'),
																			selected:(selected==opts[i])
																			}
																		);
																	}

																return res;
																}
															)()
														}
													]
												}
											]
										}
									]
								},
							{
								tag:'DD',
								className:'clear'
								}
							]
						},
					{
						id:'search-type-switcher',
						child:{
							tag:'SPAN',
							className:'advanced-search',
							child:{
								tag:'A',
								className:'js-link',
								onclick:function(){
									$this.setData('_regime','simple');
									return $this.render();
									},
								content:'Простой поиск'
								}
							}
						},
					{
						className:'submit centered distant',
						 child:{
							className:'button wide41',
							content:'<button type="submit" onfocus="blur()"><span>Найти</span></button>'
							/*child:{
								tag:'BUTTON',
								onfocus:selfBlur,
								onclick:function(){
									searchForm.submit();
									return false;
									},
								child:{
									tag:'SPAN',
									content:'Найти'
									}
								}*/
							}
						}
					]
				}
			);
	this.appendForm(searchForm);
	this.refreshPreciseSelectors=function(){
		var childFields=['hours','days'];
		for (var i=0;i<10;i++){
			var selector=$id('precise_'+i);
			if (!selector){
				return;
				}
			for (var j in childFields){
				$toggleDisable( 'precise_'+i+'_'+childFields[j],!$checked(selector));
				}
			}
		}
	this.refreshPreciseSelectors();
	return true;
	}

Search.prototype.getSwitchTypeNodes=function(prefix,fields){
	var $this=this;
	return {
			className:'type-selector',
			child:{
				tag:'UL',
				className:'type-selector',
				children:[
					{
						tag:'LI',
						className:'col-1',
						id:'type-selector-'+ROUTE_TYPE_PASSENGER,
						children:[
							{
								tag:'INPUT',
								type:'radio',
								name:'type',
								id:'type_'+ROUTE_TYPE_PASSENGER,
								value:ROUTE_TYPE_PASSENGER,
								onclick:function(){
									$this.setData('type',this.value);
									$this.appendType();
									},
								onfocus:selfBlur
								},
							{
								tag:'LABEL',
								content:'Я&nbsp;&mdash; пассажир, <strong>ищу водителей</strong>',
								params:{
									htmlFor:'type_'+ROUTE_TYPE_PASSENGER
									}
								}
							]
						},
					{
						tag:'LI',
						className:'col-2',
						id:'type-selector-'+ROUTE_TYPE_DRIVER,
						children:[
							{
								tag:'INPUT',
								type:'radio',
								name:'type',
								id:'type_'+ROUTE_TYPE_DRIVER,
								value:ROUTE_TYPE_DRIVER,
								onclick:function(){
									$this.setData('type',this.value);
									$this.appendType();
									},
								onfocus:selfBlur
								},
							{
								tag:'LABEL',
								content:'Я&nbsp;&mdash; водитель, <strong>ищу пассажиров</strong>',
								params:{
									htmlFor:'type_'+ROUTE_TYPE_DRIVER
									}
								}
							]
						}
					]
				}

			};
	}

Search.prototype.getPointNodes=function(prefix,fields){
	var
		$this=this,
		_regime=this.getData('_regime'),
		hasStreet=$this.getData(prefix+'_city_hasStreet'),
		hasSubway=$this.getData(prefix+'_city_hasSubway'),
		nodes=[];
	if (!fields){
		fields=
			(_regime=='simple')?
			{
				city:true,
				date:true
				}
			:
			{
				city:true,
				street:true,
				house:true,
				subway:true
				};
		}
	if (fields.city){
		nodes.push(
			{
				tag:'DD',
				className:'highlighted',
				children:[
					{
						tag:'LABEL',
						content:'Город / населённый пункт',
						params:{
							htmlFor:prefix+'_city'
							}
						},
					{
						tag:'INPUT',
						type:'text',
						name:prefix+'_city',
						id:prefix+'_city',
						className:'highlighted',
						value:this.getData(prefix+'_city_nameFull')
						},
					{
						tag:'SPAN',
						className:'full-options',
						onclick:function(){
							makeExtSelect(
								{
									itemName:'city',
									pagerAtBottom:true,
									onresult:function(item){
										if (!item.id){
											return false;
											}
										var prevId=$this.getData(prefix+'_city');
										if (prevId && prevId!=item.id){
											$this.setData(prefix+'_street',null);
											$this.setData(prefix+'_street_nameFull',null);
											$this.setData(prefix+'_street_pseudoFieldValue',null);
											$this.setData(prefix+'_house',null);
											$clearValue(prefix+'_house');
											$this.setData(prefix+'_subway',null);
											$this.setData(prefix+'_subway_nameFull',null);
											$this.setData(prefix+'_subway_pseudoFieldValue',null);
											}
										$this.setData(prefix+'_city',item.id);
										$this.setData(prefix+'_city_nameFull',item.name_full);
										$this.setData(prefix+'_city_pseudoFieldValue',item.name);
										$this.setData(prefix+'_city_hasStreet',!!Number(item.has_street));
										$this.setData(prefix+'_city_hasSubway',!!Number(item.has_subway));
										$this.render();
										}
									}
								);
							}
						}
					]
				}
			);
		}
	if (fields.street){
		nodes.push(
			{
				tag:'DD',
				className:'short1',
				children:[
					{
						tag:'LABEL',
						content:'Улица',
						params:{
							htmlFor:prefix+'_street'
							}
						},
					{
						tag:'INPUT',
						type:'text',
						name:prefix+'_street',
						id:prefix+'_street',
						value:hasStreet?this.getData(prefix+'_street_nameFull'):'',
						disabled:!hasStreet,
						className:!hasStreet?'disabled':''
						},
					(
					 hasStreet?
						{
							tag:'SPAN',
							className:'full-options',
							onclick:function(){
								makeExtSelect(
									{
										itemName:'street',
										extData:{
											city_id:$this.getData(prefix+'_city')
											},
										onresult:function(item){
											if (!item.id){
												return false;
												}
											$this.setData(prefix+'_street',item.id);
											$this.setData(prefix+'_street_nameFull',item.name_full);
											$this.setData(prefix+'_street_pseudoFieldValue',item.name);
											$this.render();
											}
										}
									);
								}
							}
							:
						''
						)
					]
				}
			);
		}
	if (fields.house){
		nodes.push(
			{
				tag:'DD',
				className:'short2',
				children:[
					{
						tag:'LABEL',
						content:'Номер дома',
						params:{
							htmlFor:prefix+'_house'
							}
						},
					{
						tag:'INPUT',
						type:'text',
						name:prefix+'_house',
						id:prefix+'_house',
						value:hasStreet?this.getData(prefix+'_house'):'',
						disabled:!hasStreet,
						className:!hasStreet?'disabled':''
						}
					]
				}
			);
		}

	if (fields.subway){
		nodes.push(
			{
				tag:'DD',
				children:[
					{
						tag:'LABEL',
						content:'Станция метро',
						params:{
							htmlFor:prefix+'_subway'
							}
						},
					{
						tag:'INPUT',
						type:'text',
						name:prefix+'_subway',
						id:prefix+'_subway',
						value:hasSubway?this.getData(prefix+'_subway_nameFull'):'',
						disabled:!hasSubway,
						className:!hasSubway?'disabled':''
						},
					(
					 hasSubway?
						{
							tag:'SPAN',
							className:'full-options',
							onclick:function(){
								makeExtSelect(
									{
										itemName:'subway',
										extData:{
											city_id:$this.getData(prefix+'_city')
											},
										onresult:function(item){
											if (!item.id){
												return false;
												}
											$this.setData(prefix+'_subway',item.id);
											$this.setData(prefix+'_subway_nameFull',item.name_full);
											$this.setData(prefix+'_subway_pseudoFieldValue',item.name);
											$this.render();
											}
										}
									);
								}
							}
							:
						''
						)
					]
				}
			);
		}

	if (fields.date){
		var dtDeparture=this.getData('from_date');
		nodes.push(
			{
				tag:'DD',
				children:[
					{
						tag:'LABEL',
						content:'Дата:',
						params:{
							htmlFor:prefix+'_date'
							}
						},
					{
						tag:'INPUT',
						type:'text',
						name:prefix+'_date',
						id:prefix+'_date',
						value:dtDeparture?(is_date(dtDeparture)?dtDeparture.getReadableSimple():dtDeparture.dateReadableSimpleStr()):''
						},
					{
						tag:'SPAN',
						className:'full-options calend',
						id:prefix+'_date_full-options',
						qOnclick:function(){
							$focus(prefix+'_date');
							}
						}
					]
				}
			);
		}
	if (fields.with_info){
		nodes.push(
			{
				tag:'DD',
				className:'search-form-with-info-wrap',
				children:[
					{
						tag:'INPUT',
						type:'checkbox',
						name:'with_info',
						id:'with_info',
						className:'input-checkbox',
						checked:!!Number($this.getData('with_info')),
						onclick:function(){
							$this.setData('with_info', +$checked(this));
							}
						},
					{
						tag:'LABEL',
						content:'Только маршруты с отзывами <span class="bullet"></span>',
						params:{
							htmlFor:'with_info'
							}
						}
					]
				}
			);
		}
	if (fields.time){
		nodes.push(
			{
				tag:'DD',
				className:'short1',
				children:[
					{
						tag:'LABEL',
						content:'Время:',
						params:{
							htmlFor:prefix+'_time'
							}
						},
					{
						tag:'SELECT',
						name:prefix+'_time',
						id:prefix+'_time',
						children:$this.getTimeSelectNodes($this.getData(prefix+'_time'))
						}
					]
				}
			);
		}
	return [
		{
			className:'search-point',
			children:[
				{
					tag:'DL',
					children:nodes
					},
				{
					tag:'SPAN',
					className:'clear0'
					}
				]
			}
		];
	}

Search.prototype.getTimeSelectNodes=function(selected){
	var nodes=[
		{
			tag:'OPTION',
			value:0,
			content:'любое'
			}
		];
	for (var i=1; i<24; i++){
		var
			t=String(i).setDigits()+':00',
			opt={
				tag:'OPTION',
				value:t,
				content:t
				};
		if (selected==t){
			opt.params={
				selected:true
				};
			}
		nodes.push(opt);
		}
	return nodes;
	}
Search.prototype.getData=function(property){
	if (property){
		return this.data[property];
		}
	else{
		return this.data;
		}
	}
Search.prototype.setData=function(data,val){
	if (!data){
		return false;
		}
	if (typeof data=='object'){
		for (var opt in data){
			this.data[opt]=data[opt];
			}
		}
	else{
		this.data[data]=val;
		}
	return this.data;
	}
Search.prototype.isBuilded=function(){
	return this.getData('container')?true:false;
	}

$(function(){
		showAjaxProgress();
		var rSearch=new Search();
		rSearch.setData('container',$id('search-container'));
		rSearch.setData('wrapContainer',$id('search-wrap'));
		if (is_object(TriDorogiPage.$GET) && (TriDorogiPage.$GET.from_city || TriDorogiPage.$GET.to_city)){
			var
				get=TriDorogiPage.$GET,
				p={
					cities:[],streets:[],subways:[]
					},
				params={};
			if (get.from_city){p.cities.push(get.from_city);}
			if (get.to_city){p.cities.push(get.to_city);}
			if (get.from_street){p.streets.push(get.from_street);}
			if (get.to_street){p.streets.push(get.to_street);}
			if (get.from_subway){p.subways.push(get.from_subway);}
			if (get.to_subway){p.subways.push(get.to_subway);}
			for (var i in p){
				if (p[i].join){
					params[i]=p[i].join(',')
					}
				}
			makeAjaxExt(
				{
					params:concatObjects(
						{
							todo:'getGeoDetails'
							},
						params
						),
					bs:true,
					onload:function(details){
						var addData={};
						if (details){
							if (get.from_city && details.cities[get.from_city]){
								addData.from_city_nameFull=details.cities[get.from_city].name_full;
								addData.from_city_pseudoFieldValue= details.cities[get.from_city].name;
								addData.from_city_hasStreet=!!Number(details.cities[get.from_city].has_street);
								addData.from_city_hasSubway=!!Number(details.cities[get.from_city].has_subway);
								}
							if (get.to_city && details.cities[get.to_city]){
								addData.to_city_nameFull=details.cities[get.to_city].name_full;
								addData.to_city_pseudoFieldValue=details.cities[get.to_city].name;
								addData.to_city_hasStreet=!!Number(details.cities[get.to_city].has_street);
								addData.to_city_hasSubway=!!Number(details.cities[get.to_city].has_subway);
								}
							if (get.from_street && details.streets[get.from_street]){
								addData.from_street_nameFull=details.streets[get.from_street].name_full;
								addData.from_street_pseudoFieldValue=details.streets[get.from_street].name;
								}
							if (get.to_street && details.streets[get.to_street]){
								addData.to_street_nameFull=details.streets[get.to_street].name_full;
								addData.to_street_pseudoFieldValue=details.streets[get.to_street].name;
								}
							if (get.from_subway && details.subways[get.from_subway]){
								addData.from_subway_nameFull=details.subways[get.from_subway].name_full;
								addData.from_subway_pseudoFieldValue=details.subways[get.from_subway].name;
								}
							if (get.to_subway && details.subways[get.to_subway]){
								addData.to_subway_nameFull=details.subways[get.to_subway].name_full;
								addData.to_subway_pseudoFieldValue=details.subways[get.to_subway].name;
								}
							if (get.from_street || get.to_street || get.from_subway || get.to_subway || isset(get.precise) || isset(get.precise_1_hours) || isset(get.precise_2_days) ){
								addData['_regime']='advanced';
								}
							}
						rSearch.setData(
							concatObjects(
								addData,
								TriDorogiPage.$GET
								)
							);
						if (!isNaN(TriDorogiPage.$GET['page'])){
							rSearch.setData('_page',TriDorogiPage.$GET['page']);
							}

						//rSearch.render();
						if (get.from_city || get.to_city){
							rSearch.search();
							}
						else{
							rSearch.render();
							}
						}
					}
				);
			}
		else{
			rSearch.render();
			stopShowAjaxProgress();
			}
		}
	);

function shortSearchInit(){
	var container=$id('search-container');
	if (!$id('type_'+ROUTE_TYPE_PASSENGER).checked && !$id('type_'+ROUTE_TYPE_DRIVER).checked){
		$id('type_'+ROUTE_TYPE_PASSENGER).checked=true;
		toggleClass(container,1,['type_'+ROUTE_TYPE_DRIVER,'type_'+ROUTE_TYPE_PASSENGER])
		}
	var
		pointsFields=concatObjects(
			getSearchPointsFields('from'),
			getSearchPointsFields('to')
			),
		fields=concatObjects(
			pointsFields,
			{
				type:{
					f_template:'radioGroup',
					f_onclick:function(){
						toggleClass(container,(this.value==ROUTE_TYPE_PASSENGER?1:0),['type_'+ROUTE_TYPE_DRIVER,'type_'+ROUTE_TYPE_PASSENGER])
						},
					f_onfocus:selfBlur
					}
				}
			);
	var dif=new DOCUMENT_IFORM(
		{
			form:'searchForm',
			fields:fields
			}
		);
	}

function getSearchPointsFields(prefix){
	var fields={};
	if ($id(prefix+'_city')){
		fields[prefix+'_city']={
			f_template:'city',
			f_suggest:{
				handler:PATH_INC_PROJECT_ROUTES,
				todo:'getCities',
				past:function(){
					alert('suggestComplete')
					},
				limit:15
				}
			};
		}
	if ($id(prefix+'_street')){
		fields[prefix+'_street']={
			f_template:'street'
			};
		}
	if ($id(prefix+'_house')){
		fields[prefix+'_house']={
			f_template:'house'
			};
		}
	if ($id(prefix+'_subway')){
		fields[prefix+'_subway']={
			f_template:'subway'
			};
		}
	if ($id(prefix+'_date')){
		fields[prefix+'_date']={
			f_template:'date_calendar'
			};
		}
	if ($id(prefix+'_time_hours')){
		fields[prefix+'_time_hours']={
			f_template:'hour'
			};
		}
	if ($id(prefix+'_time_minutes')){
		fields[prefix+'_time_minutes']={
			f_template:'minute'
			};
		}

	return fields;
	}


