
	addOnLoadEvent(getHotelsFromStars, changeChild, searchStart);
	
	function getHotelsFromStars() {
		
        
        $('.searchTour').click(function() {
            var curStatus = $(this).attr('sdiv');
            
            if(curStatus == 'N') {
                var divIds = $(this).attr('divid');
                var curDiv = '#' + divIds;
                
                //$('.searchTour [sdiv=Y]').removeClass('');
                //$('.searchTourCurrent').removeClass('');
                
                var otherTd  = $('.searchTourCurrent');
                var otherDiv = '#' + otherTd.attr('divid');
                //console.log(otherDiv);
                otherTd.attr('sdiv', 'N');
                otherTd.removeClass('searchTourCurrent');
                
                $(this).addClass('searchTourCurrent');
                
                $(otherDiv).hide('fast');
                $(curDiv).show('fast');
                
            }
        });
        
        // Изменение даты
        $('#frDate').change(function() {
            loadHotels(0,0,0);
        });
        
        // Изменение звезд
		$('.changeStars').click(function() {
			//var stars = $(this).val();
			// var stars = buildStars();
			// var cId = $('#selectCountry').val();
			// var tId = $('#selectTown').val();
			
			// if(tId == 0) {
				// loadHotels(0, cId, stars);
			// }else {
				// loadHotels(tId, 0, stars);
			// }
            
            disableStarsBox();
            
            loadHotels(0,0,0);
            
		});
		
        // Изменение дней от
		$('#frNDay').change(function() {
			//alert($(this).val());
			var from = parseInt($(this).val());
			var to = parseInt($('#toNDay').val());
			// alert(typeof(from));
			// alert(to);
			if(to <= from) {
				//alert(56);
				var cT = from + 1;
				$('#toNDay').val(cT);
			}
		});
        
        // Изменение типа тура (программы)
        $('#selectTour').live('change', function() {
			loadDates();
            
		});
        
        
        // Изменение страны
		$('#selectCountry').live('change', function() {
            
			var cId = $(this).val();
            //console.log(cId);
			if(cId == 0) {
				NullHotelForm();
				NullTownForm();
				NullTourForm();
			}else {
                $('.tnLd').show();
                
				var stars = buildStars();
                //console.log(stars);
				var url = '/helper/loadTownSF.php';
				$('#divSelectTown').load(url + '?cId=' + cId, function(data) {
                    $('.tnLd').hide();
					NullHotelForm();
					//alert(data);
					//$(this).unbind('change');
					//bindTown();
				});
				loadHotels(0, cId, stars);
				loadTours();
			}
		});
        
        
        // Изменение города
        $('#selectTown').live('change', function() {
			var stars = buildStars();
			var tId = $(this).val();
			var cId = $('#selectCountry').val();
			// if(tId != 0) {
				// loadHotels(tId, 0, stars);
			// }else {
                $('#selectTour').val(0);
				loadTours();
                loadDates();
                setTimeout(function() {
                    loadHotels(tId, cId, stars);
                }, 500);
			//}
		});
        
        // Изменение звезд
        
	}
	
    
    // Disable checkbox количество звезд
    function disableStarsBox()
    {
        $('.changeStars').each(function() {
            $(this).attr('disabled', true);
        });
    }
    
    // Enable checkbox количество звезд
    function enableStarsBox()
    {
        $('.changeStars').each(function() {
            $(this).attr('disabled', false);
        });
    }
    
    
	// STARS
	function buildStars() {
		var stars = '';
		$('.changeStars').each(function() {
			if($(this).is(':checked')) {
				stars += $(this).val() + ',';
			}
		});
		if(stars != '') {
			stars = stars.slice(0, -1);
		}else {
			stars = '2,3,4,5';
		}
		return stars;
	}
	
	
	
	// Загрузка дат
	function loadDates() {
		
		var tl_key = $('#selectTour').val();
		var cn_key = $('#selectCountry').val();
		var ct_key = $('#selectTown').val();
		
		var params = {
                        ct_key: ct_key,
                        cn_key: cn_key,
						tl_key: tl_key
					};
		
		var url = '/helper/loadDatesSF.php';
		$.post(url, params, function(data) {
			//alert(data);
            //console.log(data);
            
            var tmpData = data.split('$$');
            
			$('#frDate').attr('vdate', tmpData[1]);
			$('input.date').datePicker();
            
            
            //console.log(tmpData[0]);
            fillDuration(tmpData[0]);
            
            $('input.date').val('');
            //loadHotels(0,0,0);
            $('#divSelectHotel').html('');
            
            if(typeof(tmpTourData.date) != 'undefined') {
                //alert(56);
                $('#frDate').val(tmpTourData.date);
                $('#frDate').trigger('change');
                tmpTourData.date = null;
            }
            
		});
		
	}
	
	
    //подсветка продолжительности туров
    function fillDuration(dur)
    {
        var durations = dur.split('|');
        
        $('#frNDay option').each(function() {
            $(this).css('background', '#FFFFFF');
        });
        $('#toNDay option').each(function() {
            $(this).css('background', '#FFFFFF');
        });
        
        
        //console.log(durations);
        $.each(durations, function(i, val) {
            //console.log(val);
            if(val != '') {
                $('#frNDay option[value='+val+']').css('background', '#84FC78');
                $('#toNDay option[value='+val+']').css('background', '#84FC78');
            }
        });
        
    }
    
    
	// Загрузка туров
	function loadTours() {
        
        $('.tlLd').show();
        
		var cId = $('#selectCountry').val();
		var tId = $('#selectTown').val();
        
        
        
		//alert(cId);
		//alert(tId);
		var url = '/helper/loadToursSF.php';
		$('#divSelectTour').load(url + '?cId=' + cId + '&tId=' + tId, function(data) {
            $('.tlLd').hide();
			//alert(data);
			//bindTours();
            if(typeof(tmpTourData.tlkey) != 'undefined') {
                //alert(56);
                $('#selectTour').val(tmpTourData.tlkey);
                $('#selectTour').trigger('change');
                tmpTourData.tlkey = null;
            }
		});
	}
	
	// Загрузка отелей
	function loadHotels(tId, cId, stars) {
        
        var date = $('#frDate').val();
        
        if(date != '') {
            
            $('.hlLd').show();
            
            var stars = buildStars();
            var tId  = $('#selectTown').val();
            var cId  = $('#selectCountry').val();
            var trId = $('#selectTour').val();
            var date = $('#frDate').val();
            
    		var url = '/helper/loadHotelSF.php';
    		$('#divSelectHotel').load(url + '?tId=' + tId + '&cId=' + cId + '&stars=' + stars + '&date=' + date + '&trId=' + trId, function(data) {
                $('.hlLd').hide();
                enableStarsBox();
    			//alert(data);
    			//bindEvent();
    		});
        }else {
            //alert(56);
            enableStarsBox();
        }
	}
	
	function NullTownForm() {
		$('#selectTown').html('<option value="0">выберите город</option>');
	}
	
	function NullHotelForm() {
		$('#selectHotel').html('<option value="0">выберите отель</option>');
	}
	
	function NullTourForm() {
		$('#selectTour').html('<option value="0">выберите тип тура</option>');
	}
	
	// Построение select с возрастом детей
	function buildChildSelect(val) {
		var select = '<select name="age' + val + '" id="age' + val + '">';
		for(var i =0; i <= 16; i++) {
			select += '<option value="' + i + '">' + i + '</option>';
		}
		select += '</select>';
		return select;
	}
	
	// Количество и возрасты детей
	function changeChild() {
		$('#selectChild').change(function() {
			var iteration = $(this).val();
            //console.log(iteration);
			if(iteration == 0) {
				$('#divAgeChild').hide();
			}else {
				$('#divAgeChild').show();
			}
			$('#ageChild').html('');
			for(var i = 1; i <= iteration; i++) {
				var apS = buildChildSelect(i) + '&nbsp;';
				$('#ageChild').append(apS);
			}
		})
	}
	
	
    /**
     *Заполнение формы данными
     *при клике на дате тура
     */
    function showTmpDateData()
    {
        //console.log(tmpTourData);
        // Страна
        $('#selectCountry').val(tmpTourData.cnkey);
        $('#selectCountry').trigger('change');
    }
    
    
	/**
     *Поиск тура
     *
     */
	function searchStart() {
		$('#searchStart').click(function() {
			if($('#frDate').val() == '') {
				alert('Необходимо выбрать дату вылета!');
			}else if($('#selectCountry').val() == '0') {
				alert('Необходимо выбрать страну!');
			}else {
				var tmp = $('#frDate').val().split('.');
				//console.log(tmp);
				// Дата вылета
				var frDate = tmp[2] + tmp[1] + tmp[0];
				// + дней
				var toDate = $('#toDate').val();
				// Продолжительность тура от
				var frNDay = $('#frNDay').val();
				// ДО
				var toNDay = $('#toNDay').val();
				// Количество взрослых
				var adt = $('#adult').val();
				// Возрасты детей
				var age1 = $('#age1').val();
				var age2 = $('#age2').val();
				var age3 = $('#age3').val();
				var age4 = $('#age4').val();
				// Страна
				var CN_KEY = $('#selectCountry').val();
				//var CN_KEY = (cnKey == null || cnKey == 0) ? 1 : cnKey;
				
				// ГОРОД
				var CT_KEY = $('#selectTown').val();
				//var CT_KEY = (ctKey == null || ctKey == 0) ? 1 : ctKey;
				
				// Отель
				//var HD_KEY = $('#selectHotel').val();
                var HD_KEY = '';
                $('.hotelsBox').each(function() {
                    var boxChecked = $(this).is(':checked');
                    var boxIds     = $(this).val();
                    if(boxChecked) {
                        HD_KEY += boxIds + ',';
                    }
                });
                if(HD_KEY != '') {
                    HD_KEY = HD_KEY.slice(0, -1);
                }
                //console.log(HD_KEY);
                
				//var HD_KEY = (hdKey == null || hdKey == 0) ? 1 : hdKey;
				
				// ТУР
				var TL_KEY = $('#selectTour').val();
				
				// Звезды
				var HD_STARS = buildStars();
				
				// Питание
				var PN_KEY  = '';
                var pnCount = 0;
                $('.mealBox').each(function() {
                    var boxChecked = $(this).is(':checked');
                    var boxIds     = $(this).val();
                    if(boxChecked) {
                        pnCount++;
                        PN_KEY += boxIds + ',';
                    }
                });
                if(PN_KEY != '') {
                    PN_KEY = PN_KEY.slice(0, -1);
                }
                if(pnCount == 5) {
                    PN_KEY = '';
                }
                
                
				//var PN_KEY = 'isnull';
                
				
				var sendData = {
								frDate: frDate,
								toDate: toDate,
								frNDay: frNDay,
								toNDay: toNDay,
								adt: 	adt,
								age1: 	age1,
								age2:	age2,
								age3:	age3,
								age4:	age4,
								CN_KEY: CN_KEY,
								CT_KEY: CT_KEY,
								HD_KEY: HD_KEY,
                                
								TL_KEY: TL_KEY,
								PN_KEY: PN_KEY,
								HD_STARS: HD_STARS
								};
				
                
                
                
				buildForm();
				
				$.ajaxSetup({async: false});
				
				// Форма поиска тура
				// var url = '/helper/searchForm.php';
				
				// $.post(url, sendData, function(data) {
					// $('#searchFormDiv').html(data);
					// bindEventsForM();
				// });
				
				//Отправка запроса на поиск данных
				$('#previewDiv').html('<br><br><br><img src="/pict/loadingST.gif" border="0"><br>Идет загрузка...').show();
				var url = '/helper/searchTour.php';
				setTimeout(function() {
					$.post(url, sendData, function(data) {
						//alert(data);
						$('#previewDiv').html(data);
					});
				}, 1500);
				
			}
		});
	}
	
	
	function buildForm() {
		var x,y;
		if(window.innerWidth) {
			x = window.innerWidth;
		}else {
			with(document.body) {
				x = clientWidth;
			}
		}
		y = document.body.scrollHeight;
		if(!$.browser.msie) {
			x = x - 16;
		}
		var width = x + 'px';
		var height = y + 'px';
		
		var fullDiv = document.createElement('div');
		$(fullDiv).attr({
						id: 'fullDiv'
						})
					.css({
						display: 'none',
						position: 'absolute',
						top: '0px',
						left: '0px',
						width: width,
						height: height,
						border: '0px solid green',
						//background: '#333232',
						//opacity: 0.9,
						background: 'url("pict/formOverlay.png")',
						padding: '56px 0px 0px 0px',
						zIndex: 999
						});
		var table = document.createElement('table');
		$(table).attr({
						id: 'prevTable'
						})
					.css({
						width: '100%'
						});
		var tr = document.createElement('tr');
		var td = document.createElement('td');
		$(td).attr('align', 'center')
				.css({
					width: '100%',
					border: '0px solid red'
					});
		
		// Большой общий див
		var bigPrevDiv = document.createElement('div');
		$(bigPrevDiv).attr({
						id: 'bigPrevDiv'
						})
					.css({
						width: '998px',
						border: '0px solid red'
						});
						
		// маленький левый div
		var leftDiv = document.createElement('div');
		$(leftDiv).css({
						width: '26px'
						}).css('float', 'left');
		$(leftDiv).html('<img src="images/1x1.gif" width="26" height="1" border="0">');
						
		// маленький правый div с кнопкой закрыть
		var rightCloseDiv = document.createElement('div');
		$(rightCloseDiv).css({
						width: '26px',
						cursor: 'pointer'
						}).css('float', 'left');
		$(rightCloseDiv).html('<img src="/pict/closePreview.png" width="32" height="32" border="0" alt="закрыть" title="закрыть">');
		
		
		var predPreviewDiv = document.createElement('div');
		$(predPreviewDiv).attr({
							id: 'predPreviewDiv'
							})
					.css({
						width: '940px',
						height: '600px',
						//margin: '10px 15px 10px 15px',
						border: '1px solid #000',
						background: '#FFFFFF',
						overflow: 'hidden'
						})
						.css('float', 'left');
		
		var searchFormDiv = document.createElement('div');
		$(searchFormDiv).attr({
							id: 'searchFormDiv'
							})
					.css({
						width: '930px',
						//height: '100px',
						margin: '5px 0px 0px 0px',
						border: '0px solid red'
						
						});
		
		
		var previewDiv = document.createElement('div');
		$(previewDiv).attr({
							id: 'previewDiv'
							})
					.css({
						display: 'none',
						width: '930px',
						height: '555px',
						margin: '5px 0px 5px 0px',
						overflow: 'scroll',
						border: '0px solid #58577F',
						background: '#FFFFFF',
						textAlign: 'center'
						})
						//.css('float', 'left');
						
		//$(previewDiv).html('<br><br><br><img src="/pict/loadingST.gif" border="0"><br>Идет загрузка...');
		
		
		$(predPreviewDiv).append(searchFormDiv).append(previewDiv);
		
		$(bigPrevDiv).append(leftDiv).append(predPreviewDiv).append(rightCloseDiv);
		
		$(table).append($(tr).append($(td).append(bigPrevDiv)));
		$('body').append($(fullDiv).append(table));
		$(fullDiv).show();
		
		$(rightCloseDiv).bind('click', closeFullDiv);
		// $('#predPreviewDiv').bind('click', function() {
			// return false;
		// });
		// $('#previewDiv').bind('click', function() {
			// return false;
		// });
	}
	
	// Закрыть форму
	function closeFullDiv() {
		$('#fullDiv').hide();
		$('#fullDiv').remove();
	}
	
	
	
	
	
	
