$(document).ready(function(){		
		$('#touristChildList').bind('change',function(){
			var selectTouristNumChild = $(this);
			$('.peopleChild').css('visibility','hidden');
			$('.peopleChild').each(function(i){
				if (i == selectTouristNumChild.val()) return false;
				$(this).css('visibility','visible');
			});
		});
		
		$('#checkedHotel').bind('click',function(){
			var $showElement = $('#hotels').find('li > span').filter('.checkboxAreaChecked');
			if ($showElement.length > 0){
				$('#hotels').find('li').hide();
				$showElement.parents('li').show();			
			} else $('#hotels').find('li').show();
			$('.scroll').jScrollPane({showArrows:true, scrollbarWidth:23, dragMaxHeight:57});
		});

		//Обработка кол-ва маленьких туристов
		$('#touristChildList').val(0);
		$('#touristChildList').trigger('change');

		$('#touristAdultList').val(2);
		$('#touristAdultList').trigger('change');

		$('#nights_from > option').remove();
		for (i = 4; i < 21; i++){
			$('#nights_from, #nights_till').append('<option value="'+i+'">'+i+'</option>');
		}
		$('#nights_from, #nights_till').find('option[value=7]').attr('selected','true');
		$('#nights_from, #nights_till, #touristAdultList, #touristChildList, #areas_agency').customSelect();

		$('#date_from').datepicker({
			showOn: "button",
			gotoCurrent:true,
			minDate:1,
			buttonImage: '/images/date.png',
			buttonImageOnly: true,
			onSelect: function(dateText, inst) {
				var RegExp = /^([0-9]{2})\.([0-9]{2})\.([0-9]{4})$/;
				var aData = RegExp.exec(dateText);				
				$('#date_till').val(dateText);
				$("#date_till").datepicker( "option", "minDate",new Date(aData[3],parseInt(aData[2])-1,aData[1]));
			}
		});

		$('#date_till').datepicker({
			showOn: "button",
			gotoCurrent:true,
			minDate:1,
			buttonImage: '/images/date.png',
			buttonImageOnly: true
		});

		
		//Регистрация событий
		$('#cityout').bind('change',function(){
			DICTIONARY.getCountries($(this).val());
		});

		$('#country').bind('change',function(){
			DICTIONARY.getDynamicDictionary($(this).val());
		});

		//Объект для управления словорями
		DICTIONARY = {
			hotelLabelShow:[],
			getCountries:function(cityout_id){
				$.get('/json/countries/'+cityout_id+'/',function(data){
					$('#country > option').remove();
					$(data).each(function(i,item){
						$('#country').append('<option value="'+item.id+'">'+item.country_name+'</option>');
					});
					$('#country > option[value=1152]').attr('selected','true');
					$('#country').customSelect();
					$('#country').change();					
				},'json')
			},
			getDynamicDictionary:function(country_id){
				$.get('/json/getdynamicdictionaries/'+country_id+'/',function(data){
					$('#hotels').html('');
					$('#area').html('');

					DICTIONARY.hotels = data['hotel'];

					$('#hotels').html('');
					$(data['hotel']).each(function(i,item){
						$('#hotels').append('<li id="hotel_'+item.id+'" area="'+item.area_group_id+'" star="'+item.stars_category_id+'"><input type="checkbox" class="customCheckbox" name="hotel" value="'+item.id+'" /><label>'+item.hotel_name+'</label></li>');
					});

					$('#area').html('');
					$(data['area_group']).each(function(i,item){
						$('#area').append('<li><input type="checkbox" class="customCheckbox" name="area_group_name" value="'+item.id+'" /><label>'+item.area_group_name+'</label></li>');
					});

					$('#feeding').html('');
					$(data['feeding']).each(function(i,item){
						$('#feeding').append('<li><input type="checkbox" class="customCheckbox" name="feeding" value="'+item.id+'" /><label>'+item.feeding_name+'</label>');
					});

					$('#hotelstar').html('');
					$(data['hotelstar']).each(function(i,item){
						$('#hotelstar').append('<li><input type="checkbox" class="customCheckbox" name="hotelstar" value="'+item.id+'" /><label>'+item.hotel_category_name+'</label>');
					});

					$('ul[id^=operators_block_]').html('');
					$(data['operator']).each(function(i,item){
						var h = ((i + 1) / 4).toString().split('.');
						switch(h[1]){
							case '25':
								$('#operators_block_1').append('<li><input type="checkbox" class="customCheckbox" name="operator" value="'+item.id+'" /><label>'+item.operator_name+'</label>');
							break;
							case '5':
								$('#operators_block_2').append('<li><input type="checkbox" class="customCheckbox" name="operator" value="'+item.id+'" /><label>'+item.operator_name+'</label>');
							break;
							case '75':
								$('#operators_block_3').append('<li><input type="checkbox" class="customCheckbox" name="operator" value="'+item.id+'" /><label>'+item.operator_name+'</label>');
							break;							
							default:
								$('#operators_block_4').append('<li><input type="checkbox" class="customCheckbox" name="operator" value="'+item.id+'" /><label>'+item.operator_name+'</label>');
							break;
						}						
					});
					
					$('input.customCheckbox').customCheckbox();
					$('.scroll').jScrollPane({showArrows:true, scrollbarWidth:23, dragMaxHeight:57});

					$('#hotelstar').find('span').live('click',function(){
						var $elements = $('#hotelstar').find('input:checked');

						if (DICTIONARY.hotelLabelShow.length){
							DICTIONARY.hotelLabelShow.hide();
							if ($elements.length){
								$elements.each(function(){
									DICTIONARY.hotelLabelShow.filter('li[star='+$(this).val()+']').show();
								});
							} else {
								DICTIONARY.hotelLabelShow.filter('li').show();
							}
						} else {							
							$('#hotels').find('li').hide();
							if ($elements.length){
								$elements.each(function(){
									$('#hotels').find('li[star='+$(this).val()+']').show();
								});
							} else $('#hotels').find('li').show();
						}
						$('.scroll').jScrollPane({showArrows:true, scrollbarWidth:23, dragMaxHeight:57});
					});

					$('#area').find('span').live('click',function(){
						$('#hotels').find('li').hide();
						var $elementsArea = $('#area').find('input:checked');
						var $elementsStar = $('#hotelstar').find('input:checked');
						console.log($(this).val());
						if ($elementsArea.length){
							$elementsArea.each(function(){
								DICTIONARY.hotelLabelShow = $('#hotels').find('li[area='+$(this).val()+']').show()
								if ($elementsStar.length){
									DICTIONARY.hotelLabelShow.hide();
									$elementsStar.each(function(){
										DICTIONARY.hotelLabelShow.filter('li[star='+$(this).val()+']').show();
									});
								}
							});							
						} else {
							$('#hotels').find('li').hide();
							if ($elementsStar.length){
								$elementsStar.each(function(){
									$('#hotels').find('li[star='+$(this).val()+']').show();
								});
							} else $('#hotels').find('li').show();
							DICTIONARY.hotelLabelShow = [];
						}
						$('.scroll').jScrollPane({showArrows:true, scrollbarWidth:23, dragMaxHeight:57});
					});
				},'json');
			}
		}

		$.get('/json/getstaticdictionaries/',function(data){
			$(data['cityout']).each(function(i,item){
				$('#cityout').append('<option value="'+item.id+'">'+item.city_name+'</option>');
			});
			
			$('#cityout > option[value=2062]').attr('selected','true');			

			$(data['currency']).each(function(i,item){
				$('#currency').append('<option value="'+item.id+'">'+item.currency_name+'</option>');
			});
			$('#currency > option[value=35]').attr('selected','true');
			$('#cityout, #currency').customSelect();

			DICTIONARY.getCountries($('#cityout').val());
		},'json');

		$('#hotel_autocomlete').bind('keyup',function(){
			var hotel_autocomplete_text = $(this).val();
			if (hotel_autocomplete_text == '') {
				$('#hotels > li[id^=hotel_]').show();
			} else {				
				$(DICTIONARY.hotels).each(function(i,item){
					if (item.hotel_name.indexOf(hotel_autocomplete_text.toUpperCase()) == -1) $('#hotel_'+item.id).hide();
					else $('#hotel_'+item.id).show();
				})
			}
		});

		TABMENU = {
			count:0,
			elements:[],
			selectedElement:[],
			activeTab:'',
			getActiveTab:function(){
				return this.activeTab;
			},
			add:function(tourObj){
				TABMENU.elements['tabmenu_'+this.count] = tourObj;
				tourObj.tabMenuId = 'tabmenu_'+this.count;
				
				if ($('.tab-menu > li').length > 2){
					$('#'+$('.tab-menu > li').get(0).id).remove();
				}				
				$('.tab-menu').find('a').removeClass('active');
				$('.tab-menu').append('<li id="tabmenu_'+this.count+'"><a href="#">Поиск №'+(this.count+1)+'</a></li>');
				
				this.active('tabmenu_'+this.count);
				$('#tabmenu_'+this.count).bind('dblclick',['tabmenu_'+this.count],this.select);
				$('#tabmenu_'+this.count).find('a').bind('click',function(){
					TABMENU.active($(this).parent('li').attr('id'));
					return false;
				});				
				this.count++;
			},
			active:function(objId){
				this.activeTab = objId;
				$('.tab-menu').find('a').removeClass('active');
				$('#'+objId).find('a').addClass('active');
				$('#pecent_text').html(TABMENU.elements[objId].pecent_text+'%');
				$('#pecent_progressbar').css('width',TABMENU.elements[objId].pecent_text+'%');
				$('#div_result').html('');
				$('#div_result').html(TABMENU.elements[objId].divResult);
				TABMENU.elements[objId].checkNavPage();
			},
			select:function(objId){
				var search = 0;
				for (var i = 0; i < this.selectedElement.length; i++){
					if (objId == this.selectedElement[i]){
						search = 1;
						break;
					}
				}				
				if (!search){
					this.selectedElement.push(objId);
					$('#'+objId).addClass('selected');
				}
			},
			merge:function(){
				var oTOUR = new TOUR();
				oTOUR.init();
				var aSession = new Array();

				if (this.selectedElement.length){
					for (var i = 0; i < this.selectedElement.length; i++){
						aSession.push(this.elements[this.selectedElement[i]].sessionId);
					}
				} else {
					for(var sv in this.elements){
						if (this.elements[sv]) aSession.push(this.elements[sv].sessionId);
					}
				}

				oTOUR.checkStatus(aSession.join('|'));
				for(var sv in this.elements){
					TABMENU.del(sv);
				}
				TABMENU.add(oTOUR);								
			},
			del:function(objId){
				$('#'+objId).remove();
				TABMENU.elements[objId] = null;
			}
		}

		$('#mergeResult').bind('click',function(){
			TABMENU.merge();
			return false;
		});

		//Отправка запроса на поиск на сервер
		$('#button_search').bind('click',function(){
			var Data = {};			
			$('#form_search, #areaOperators, #filter_submit').find('input[type=text],input:checked,select').each(function(){
				if ($(this).attr('name') && $(this).val()){
					if (Data[$(this).attr('name')]) {						
						Data[$(this).attr('name')] += ','+$(this).val();
					} else Data[$(this).attr('name')] = $(this).val();
				}
			});

			$.post('/search/',Data,function(data){
				if (data.status == 'successfully'){
					$('.results-head, .results').removeClass('hide');
					var oTOUR = new TOUR();
					oTOUR.init();
					oTOUR.checkStatus(data.toursession_id);
					TABMENU.add(oTOUR);
					$('#button_search').blur();
				}
			},'json');
		});

		$('#areaOperatorsButton').bind('click',function(){
			$('#areaOperators').toggleClass('in');
		});

		function TOUR(){
			this.page = 1;
			this.count = 0;
			this.pagesnum = 0;
			this.statusResult = 0;
			this.init = function (){
				this.page = 1;
				this.count = 0;
				this.statusResult = 0;
			}

			this.checkStatus = function(sessionId){
				this.sessionId = sessionId;
				_this = this;
				$.post('/search/checkstatus/',{toursession_id:this.sessionId},function(data){
					if (data){
						_this.pecent_text = data.percent;						
						if (data.tournum == 'all'){
							if (TABMENU.getActiveTab() == _this.tabMenuId){
								$('#pecent_text').html('100%');
								$('#pecent_progressbar').css('width','100%');
							}
							_this.pagesnum = data.pagesnum;
							_this.checkNavPage();
							if (!_this.statusResult) _this.getResult(1);
						} else {
							if (TABMENU.getActiveTab() == _this.tabMenuId){
								$('#pecent_text').html(data.percent+'%');
								$('#pecent_progressbar').css('width',data.percent+'%');
							}
							
							if (parseInt(data.tournum) > 20) {								
								_this.count++;
							}
							if (_this.count == 1){
								_this.getResult(1);
								_this.statusResult = 1;
								_this.checkNavPage();
							}
							if (_this.statusResult) window.setTimeout(function(){_this.checkStatus(_this.sessionId);},3000);
							else window.setTimeout(function(){_this.checkStatus(_this.sessionId);},1000);
						}						
					} else {
						alert('ERROR');
					}
				},'json')
			}

			this.checkNavPage = function(){
				//Активизация стрелок
				if (this.pagesnum == this.page) {
					$('#page_next').addClass('next-dis');
					if (this.page-1 > 1){
						$('#page_prev').removeClass('prev-dis');
					} else if (this.page-1 == 1) {
						$('#page_prev').addClass('prev-dis');
					}
				} else if (this.pagesnum > this.page){
					$('#page_next').removeClass('next-dis');
					if (this.page-1 > 1){
						$('#page_prev').removeClass('prev-dis');
					} else if (this.page-1 == 1) {
						$('#page_prev').addClass('prev-dis');
					}
				}
			}

			this.getResult = function(page){
				this.page = page;
				_this = this;
				$('#div_result').html('');
				$.post('/search/getresult/',{'toursession_id':this.sessionId,'page':page},function(data){
					$('#div_result').html(data);
					_this.divResult = data;					
				});
			}
			this.next = function(){
				if (this.pagesnum == this.page+1) {
					this.getResult(this.page+1);
					$('#page_next').addClass('next-dis');
					$('#page_prev').removeClass('prev-dis');
				} else if (this.pagesnum > this.page){
					this.getResult(this.page+1);
					$('#page_next').removeClass('next-dis');
					$('#page_prev').removeClass('prev-dis');
				}
			},
			this.prev = function(){
				if (this.page-1 > 1){
					this.getResult(this.page-1);
					$('#page_prev').removeClass('prev-dis');
					$('#page_next').removeClass('next-dis');
				} else if (this.page-1 == 1) {
					this.getResult(this.page-1);
					$('#page_next').removeClass('next-dis');
					$('#page_prev').addClass('prev-dis');
				}
			}
		}

		$('#page_prev').bind('click',function(){
			TABMENU.elements[TABMENU.getActiveTab()].prev();
		});

		$('#page_next').bind('click',function(){
			TABMENU.elements[TABMENU.getActiveTab()].next();
		});
});

