$(document).ready(function(){       // по завершению загрузки страницы

	var countryid = $("#country").val();

	$("#country").change(function(){
		var countryid = $(this).val();
		$('#all_region input:checkbox, #all_hotels input:checkbox').attr("checked","checked");
		
		$.post("tours_form.php", { country: countryid, resorts: "all", hotelcat: "all", hotels: "all", meals: "all" }, function(xml){  // загрузку XML из файла
			$('#regions_container > *, #hotels_container > *, #meals > *, #stars > *').remove();
			$("span#countrykeys").attr('title', countryid);
			
			$(xml).find('resort').each(function(){       // заполняем DOM элемент данными из XML
				$('#regions_container').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'" name="region[]" checked><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')
			});
			
			$(xml).find('hotel').each(function(){       // заполняем DOM элемент данными из XML
        		$('#hotels_container').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'" name="hotel[]"><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')		
        	});
			
			$(xml).find('hotelcat').each(function(){       // заполняем DOM элемент данными из XML
				$('#stars').append('<input type="checkbox" id="'+ $(this).find('name').text() +'" value="'+ $(this).find('name').text() +'"><label for="'+ $(this).find('name').text() +'">'+ $(this).find('name').text() +'</label>')
			});
			
			$(xml).find('meal').each(function(){       // заполняем DOM элемент данными из XML
				$('#meals').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'"><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')
			});
		});
	});
	
	var count;
	var col = $("#col").attr("title");
	var max = $("#max").attr("title");

	
	$('#start').livequery(function(){
		$(this).click(function() {
			var countryid = $("span#countrykeys").attr("title");
			var resorts = '';
			var resortslist = null;
			var hotels = '';
			var hotelslist = null;
			resortslist = $('#regions_container input:checkbox:checked');
			resortslist.each( function(ind) {
				resorts += $(this).val();
				if (ind < resortslist.length - 1) resorts +=',';
			});
			hotelslist = $('#hotels_container input:checkbox:checked');
			hotelslist.each( function(ind) {
				hotels += $(this).val();
				if (ind < hotelslist.length - 1) hotels +=',';
			});
			
			var city = $('select#city option:selected').val();
			
			var depfrom = $('#from').val();
			var depto = $('#to').val();
			
			var durfrom = $('select#duration_from option:selected').val();
			var durto = $('select#duration_to option:selected').val();
			
			var hotcat = '';
			var hotcatlist = null;
			
			hotcatlist = $('#stars input:checkbox:checked');
			hotcatlist.each( function(ind) {
				hotcat += $(this).val();
				if (ind < hotcatlist.length - 1) hotcat +=',';
			});
			
			var coast = $('#coast').val();
			
			var meals = '';
			var mealslist = null;
			
			var residence = $('#residence').val();
			
			mealslist = $('#meals input:checkbox:checked');
			mealslist.each( function(ind) {
				meals += $(this).val();
				if (ind < mealslist.length - 1) meals +=',';
			});
			
			var i = 0;
			
			$.post("tours_search.php", { country: countryid, resorts: resorts, depfrom: depfrom, depto: depto, durfrom: durfrom, durto: durto, hotelcat: hotcat, coast: coast, meals: meals, hotel: hotels, residence: residence, city: city }, function(xml){  // загрузку XML из файла
																																																					
				$('div.tour_result').show();
				$('table#tour_result > *').remove();
				$('div#navigation > *').remove();
				count = $(xml).find('count').text();

				// alert("Найдено туров: " +count+ ". Все вылеты из Санкт-Петербурга. Для некоторых авиакомпаний не включен топливный сбор. Если нужны визы, они оплачиваются отдельно. Актуальность проверяйте по телефону 777-77-30.");
				$("#col").attr("title", count);
				max = Math.ceil(count/30);
				$("#max").attr("title", max);
				i = $(xml).find('tour').size();
				
				if (i != 0) { $('table#tour_result').append('<tr><th>Заезд</th><th>Ночей</th><th>Регион</th><th>Отель</th><th>Пансион</th><th>Размещение</th><th nowrap>Цена (за номер), рубли</th></tr>')}
				else { $('table#tour_result').append('<tr><td colspan="10" class="hotel" style="border-bottom:0px;">По вашему запросу туров не найдено.</td></tr>')}	
				$(xml).find('tour').each(function(){       // заполняем DOM элемент данными из XML
					if ($(this).find('hotellink').text() != '') {
	    	    	$('#tour_result').append('<tr class="'+ $(this).find('trcolor').text() +'"><td>'+ $(this).find('date').text() +'</td><td>'+ $(this).find('night').text() +'</td><td>'+ $(this).find('region').text() +'</td><td class="hotel"><a href="'+$(this).find('hotellink').text()+'" target="_blank">'+ $(this).find('hotel').text() +' '+ $(this).find('star').text() +'</a><br><span>'+ $(this).find('room').text() +'</span></td><td>'+ $(this).find('meals').text() +'</td><td>'+ $(this).find('residence').text() +'</td><td>'+ $(this).find('price').text() +'</td></tr>')}
					else {
					$('#tour_result').append('<tr class="'+ $(this).find('trcolor').text() +'"><td>'+ $(this).find('date').text() +'</td><td>'+ $(this).find('night').text() +'</td><td>'+ $(this).find('region').text() +'</td><td class="hotel">'+ $(this).find('hotel').text() +' '+ $(this).find('star').text() +'<br><span>'+ $(this).find('room').text() +'</span></td><td>'+ $(this).find('meals').text() +'</td><td>'+ $(this).find('residence').text() +'</td><td>'+ $(this).find('price').text() +'</td></tr>')}
				});
				
				$('div#navigation').append('<table align="center"><tr><td><div title="1" class="back" id = "buttonback" ><img src="/templates/Default/images/back.gif" width="27" height="26"></div></td><td><div title="1" id = "buttonnext" class="next" style="float:left;"><img src="/templates/Default/images/next.gif" width="27" height="26""></div></td></tr></table>');
				$('div.tour_result, div#navigation').fadeIn();	
				
				var page = backpage = $("#buttonnext").attr("title");$("#buttonback").css({"display":"none"}); 
				if(page == max || i == 0) {$("#buttonnext").css({"display":"none"});}
				$("#buttonback").attr({title:backpage}); // Вот мы сохранили в атрибут элемента нужные нам данные
				$("#buttonnext").attr({title:page});

			}, 'xml');   // указываем явно тип данных  				
			
		});
			
	});
	
	


	
	$('#buttonnext').livequery(function(){
		$(this).click(function() { // Используем это для перехода по номерам страинц
			var countryid = $("span#countrykeys").attr("title");
			var data = $("#col").attr("title");
			max = Math.ceil(data/30);
			if(data <= 30){return false}
			var page = $("#buttonnext").attr("title");
			if(page < max) {++page;} // Увеличиваем количество на 1 чтобы следующие данные были новыми
			$("#"+page).css("color","#f2e7c6"); // Подсветка страницы
			$("#"+page).css("font-weight","bold");
			var backpage = $("#buttonnext").attr("title"); // 
			$("#buttonback").css({"display":"block"}); 
			$("#buttonback").attr({title:backpage}); 
			if(page == max) {$("#buttonnext").css({"display":"none"});} // Если последняя страница, то скрываем кнопку
			$("#buttonnext").attr({title:page}); // Сохраняем значение в элементе для последующих запросов
			
			var city = $('select#city option:selected').val();
			
			var resorts = '';
			var resortslist = null;
			var hotels = '';
			var hotelslist = null;
			resortslist = $('#regions_container input:checkbox:checked');
			resortslist.each( function(ind) {
				resorts += $(this).val();
				if (ind < resortslist.length - 1) resorts +=',';
			});
			hotelslist = $('#hotels_container input:checkbox:checked');
			hotelslist.each( function(ind) {
				hotels += $(this).val();
				if (ind < hotelslist.length - 1) hotels +=',';
			});
			
			var depfrom = $('#from').val();
			var depto = $('#to').val();
			
			var durfrom = $('select#duration_from option:selected').val();
			var durto = $('select#duration_to option:selected').val();
			
			var hotcat = '';
			var hotcatlist = null;
			
			hotcatlist = $('#stars input:checkbox:checked');
			hotcatlist.each( function(ind) {
				hotcat += $(this).val();
				if (ind < hotcatlist.length - 1) hotcat +=',';
			});
			
			var coast = $('#coast').val();
			
			var meals = '';
			var mealslist = null;
			
			mealslist = $('#meals input:checkbox:checked');
			mealslist.each( function(ind) {
				meals += $(this).val();
				if (ind < mealslist.length - 1) meals +=',';
			});
			
			var residence = $('#residence').val();
			
			$.post("tours_search.php", { col: page, country: countryid, resorts: resorts, depfrom: depfrom, depto: depto, durfrom: durfrom, durto: durto, hotelcat: hotcat, coast: coast, meals: meals, hotel: hotels, residence: residence, city: city}, function(xml){  // загрузку XML из файла
				$('table#tour_result > *').remove();
				i = $(xml).find('tour').size();
				if (i != 0) { $('table#tour_result').append('<tr><th>Заезд</th><th>Ночей</th><th>Регион</th><th>Отель</th><th>Пансион</th><th>Размещение</th><th nowrap>Цена (за номер)</th></tr>')}
				else { $('table#tour_result').append('<tr><td colspan="10" class="hotel" style="border-bottom:0px;">По вашему запросу туров не найдено.</td></tr>')}	
				$(xml).find('tour').each(function(){       // заполняем DOM элемент данными из XML
					if ($(this).find('hotellink').text() != '') {
	    	    	$('#tour_result').append('<tr class="'+ $(this).find('trcolor').text() +'"><td>'+ $(this).find('date').text() +'</td><td>'+ $(this).find('night').text() +'</td><td>'+ $(this).find('region').text() +'</td><td class="hotel"><a href="'+$(this).find('hotellink').text()+'" target="_blank">'+ $(this).find('hotel').text() +' '+ $(this).find('star').text() +'</a><br><span>'+ $(this).find('room').text() +'</span></td><td>'+ $(this).find('meals').text() +'</td><td>'+ $(this).find('residence').text() +'</td><td>'+ $(this).find('price').text() +'</td></tr>')}
					else {
					$('#tour_result').append('<tr class="'+ $(this).find('trcolor').text() +'"><td>'+ $(this).find('date').text() +'</td><td>'+ $(this).find('night').text() +'</td><td>'+ $(this).find('region').text() +'</td><td class="hotel">'+ $(this).find('hotel').text() +' '+ $(this).find('star').text() +'<br><span>'+ $(this).find('room').text() +'</span></td><td>'+ $(this).find('meals').text() +'</td><td>'+ $(this).find('residence').text() +'</td><td>'+ $(this).find('price').text() +'</td></tr>')}
				});
			$('div.tour_result, div#navigation').fadeIn();	
			}, 'xml');   // указываем явно тип данных 
   		});
	});
	
	
	$('#buttonback').livequery(function(){
		$(this).click(function() { // Используем это для перехода по номерам страинц
		var countryid = $("span#countrykeys").attr("title");
		var data = $("#col").attr("title");
		max = Math.ceil(data/30);
		if(data <= 30){return false} // Если данных меньше чем нам нужно, то прекращаем вывод
		// Так как мы возвращаемся назад, то нужно
		// для перехода вперед уменьшить значение на один
		var page = $("#buttonnext").attr("title")-1; 
		$("#"+page).css("color","#f2e7c6"); // Используем это для перехода по номерам страинц
		$("#"+page).css("font-weight","bold");
		if(page == 1) {$("#buttonback").css({"display":"none"}); // Если первая страница, то 
		$("#buttonnext").css({"display":"block"});} // убираем кнопку "назад"
		if(page > 1) {$("#buttonback").css({"display":"block"}); //Если страница больше чем 
		$("#buttonnext").css({"display":"block"});} // первая то выводим кнопку назад

		$("#buttonnext").attr({title:page});
			var resorts = '';
			var resortslist = null;
			var hotels = '';
			var hotelslist = null;
			resortslist = $('#regions_container input:checkbox:checked');
			resortslist.each( function(ind) {
				resorts += $(this).val();
				if (ind < resortslist.length - 1) resorts +=',';
			});
			hotelslist = $('#hotels_container input:checkbox:checked');
			hotelslist.each( function(ind) {
				hotels += $(this).val();
				if (ind < hotelslist.length - 1) hotels +=',';
			});
			
			var city = $('select#city option:selected').val();
			
			var depfrom = $('#from').val();
			var depto = $('#to').val();
			
			var durfrom = $('select#duration_from option:selected').val();
			var durto = $('select#duration_to option:selected').val();
			
			var hotcat = '';
			var hotcatlist = null;
			
			hotcatlist = $('#stars input:checkbox:checked');
			hotcatlist.each( function(ind) {
				hotcat += $(this).val();
				if (ind < hotcatlist.length - 1) hotcat +=',';
			});
			
			var coast = $('#coast').val();
			
			var meals = '';
			var mealslist = null;
			
			mealslist = $('#meals input:checkbox:checked');
			mealslist.each( function(ind) {
				meals += $(this).val();
				if (ind < mealslist.length - 1) meals +=',';
			});
					
			var residence = $('#residence').val();

			$.post("tours_search.php", { col: page, country: countryid, resorts: resorts, depfrom: depfrom, depto: depto, durfrom: durfrom, durto: durto, hotelcat: hotcat, coast: coast, meals: meals, hotel: hotels, residence: residence, city: city}, function(xml){  // загрузку XML из файла
				$('table#tour_result > *').remove();
				i = $(xml).find('tour').size();
				if (i != 0) { $('table#tour_result').append('<tr><th>Заезд</th><th>Ночей</th><th>Регион</th><th>Отель</th><th>Пансион</th><th>Размещение</th><th nowrap>Цена (за номер)</th></tr>')}
				else { $('table#tour_result').append('<tr><td colspan="10" class="hotel" style="border-bottom:0px;">По вашему запросу туров не найдено.</td></tr>')}	
				$(xml).find('tour').each(function(){       // заполняем DOM элемент данными из XML
					if ($(this).find('hotellink').text() != '') {
	    	    	$('#tour_result').append('<tr class="'+ $(this).find('trcolor').text() +'"><td>'+ $(this).find('date').text() +'</td><td>'+ $(this).find('night').text() +'</td><td>'+ $(this).find('region').text() +'</td><td class="hotel"><a href="'+$(this).find('hotellink').text()+'" target="_blank">'+ $(this).find('hotel').text() +' '+ $(this).find('star').text() +'</a><br><span>'+ $(this).find('room').text() +'</span></td><td>'+ $(this).find('meals').text() +'</td><td>'+ $(this).find('residence').text() +'</td><td>'+ $(this).find('price').text() +'</td></tr>')}
					else {
					$('#tour_result').append('<tr class="'+ $(this).find('trcolor').text() +'"><td>'+ $(this).find('date').text() +'</td><td>'+ $(this).find('night').text() +'</td><td>'+ $(this).find('region').text() +'</td><td class="hotel">'+ $(this).find('hotel').text() +' '+ $(this).find('star').text() +'<br><span>'+ $(this).find('room').text() +'</span></td><td>'+ $(this).find('meals').text() +'</td><td>'+ $(this).find('residence').text() +'</td><td>'+ $(this).find('price').text() +'</td></tr>')}
				});
			$('div.tour_result, div#navigation').fadeIn();	
			}, 'xml');   // указываем явно тип данных 
		});																																																												
	});
	
	
	$('#regions_container input:checkbox').livequery(function(){
		$(this).change(function() {
			$('#all_region').attr("checked","");
			var countryid = $("span#countrykeys").attr("title");
			var res = '';
			var list = null;
   			list = $('#regions_container input:checkbox:checked');
			list.each( function(ind) {
				res += $(this).val();
				if (ind < list.length - 1) res +=',';
			});
			$.post("tours_form.php", { country: countryid, resorts: res}, function(xml){  // загрузку XML из файла
				$('#hotels_container > *, #stars > *, #meals > *').remove();
				
				$(xml).find('hotel').each(function(){       // заполняем DOM элемент данными из XML
        			$('#hotels_container').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'" name="hotel[]"><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')		
        		});
				
				$(xml).find('meal').each(function(){       // заполняем DOM элемент данными из XML
	    	    	$('#meals').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'"><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')
	        	});
				
				$(xml).find('hotelcat').each(function(){       // заполняем DOM элемент данными из XML
	    	    	$('#stars').append('<input type="checkbox" id="'+ $(this).find('name').text() +'" value="'+ $(this).find('name').text() +'"><label for="'+ $(this).find('name').text() +'">'+ $(this).find('name').text() +'</label>')
	        	});
				
		    }, 'xml');   // указываем явно тип данных  
		});
	});
	
	$('#stars input:checkbox').livequery(function(){
		$(this).change(function() {
			var countryid = $("span#countrykeys").attr("title");
			var res = '';
			var cat = '';
			var list = null;
			var catlist = null;
   			list = $('#regions_container input:checkbox:checked');
			catlist = $('#stars input:checkbox:checked');
			list.each( function(ind) {
				res += $(this).val();
				if (ind < list.length - 1) res +=',';
			});
			catlist.each( function(ind) {
				cat += $(this).val();
				if (ind < catlist.length - 1) cat +=',';
			});
			$.post("tours_form.php", { country: countryid, resorts: res, hotelcat: cat}, function(xml){  // загрузку XML из файла
				$('#hotels_container > *, #meals > *').remove();
				
				$(xml).find('hotel').each(function(){       // заполняем DOM элемент данными из XML
        			$('#hotels_container').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'" name="hotel[]"><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')		
        		});
				
				$(xml).find('meal').each(function(){       // заполняем DOM элемент данными из XML
	    	    	$('#meals').append('<div><input type="checkbox" id="'+ $(this).find('value').text() +'" value="'+ $(this).find('value').text() +'"><label for="'+ $(this).find('value').text() +'">'+ $(this).find('name').text() +'</label></div>')
	        	});
				
		    }, 'xml');   // указываем явно тип данных  
		});
	});
	
	$("#all_region").change(function(){
		if($(this).is(":checked")){
			$('#regions_container input:checkbox').attr("checked","checked");
		} else {
			$('#regions_container input:checkbox').attr("checked","");
		}
	});
	
	$('#hotels_container input:checkbox').click(function(){
		$('#all_hotels').attr("checked","");
	});
	
	
	$("#all_hotels").change(function(){
		if($(this).is(":checked")){
			$('#hotels_container input:checkbox').attr("checked","checked");
		} else {
			$('#hotels_container input:checkbox').attr("checked","");
		}
	});
	
	$("#tour_search").bind("ajaxSend", function(){
		$('#tour_search input, select').attr('disabled', 'disabled');
		$('#tours_loading').fadeIn();
		$('div.tour_result, div#navigation').fadeOut();
		
	}).bind("ajaxSuccess", function(){
		$('#tour_search input, select').attr('disabled', '');
		$('#tours_loading').fadeOut();
	});
	
	
	

	 
});
