var changingLocation = false;

$(document).ready(function(){
	$("input#autocomplete").autocomplete({
		source:function(request, response) {
			$.ajax({
				url:"/data/search/",
				dataType: "jsonp",
				data: {
					featureClass: "P",
					style: "full",
					maxRows: 10,
					name_startsWith: request.term
				},
				success: function(data) {
					response($.map(data.data, function(item) {
						return {
							label: '<div class="search-name"><nobr>'+item.name+((item.stars)?(' <span class="stars">'+item.stars+'</span>'):(''))+'</nobr></div>'+((item.parent)?('<div class="search-descr"><nobr>'+item.parent+'</nobr></div>'):('')),
							value: item.name,
							path: item.path
						}
					}));
				}
			})
		},
		minLength: 2,
		select: function(event, ui) {
			changingLocation = true;
			document.location = '/travel/'+ui.item.path+'/';
		}
	});
	$("input#autocomplete").keypress(function(event) {
		if(event.keyCode == '13' && !changingLocation) {
			document.location = '/search?q='+event.target.value;
		}
	});
	$("input#autocomplete").focus(function(event) {
		if(event.target.value == 'Поиск...') event.target.value = '';
	});
	$("input#autocomplete").blur(function(event) {
		if(event.target.value == '') event.target.value = 'Поиск...';
	});
	$(".handler").click(function(event){
		var spec_prices = $(this).next().find('.prices');
		if(spec_prices.length && !$(spec_prices[0]).html()) {
			$(spec_prices[0]).html('<b>Загрузка цен...</b>');
			$(spec_prices[0]).load('/data/get_period_prices/'+$(this).attr('value')+'/RUB/spec/', function(responseText, textStatus) {
//
			});
		}
		$(this).next().toggle();
	});
	$(".handler").mouseover(function(event){
		$(this).parent().addClass('over');
	});
	$(".handler").mouseout(function(event){
		$(this).parent().removeClass('over');
	});
	$(".group_name").click(function(event){
		$(this).next().toggle();
		$(this).toggleClass('group_expanded');
	});
	$(".group_name").mouseover(function(event){
		$(this).addClass('over');
	});
	$(".group_name").mouseout(function(event){
		$(this).removeClass('over');
	});
	
	$(".prices .periods select").change(function(event) {
		$('.prices .period_box').load('/data/get_period_prices/'+$(this).val()+'/'+$(".currency_buttons button.pressed").val()+'/');
	});
	
	$(".currency_buttons button").click(function(event) {
		if(!$(this).hasClass('pressed')) {
			$(".currency_buttons button.pressed").each(function(item) {
				$(this).removeClass('pressed');
			});
			$(this).addClass('pressed');
			$('.prices .period_box').load('/data/get_period_prices/'+$(".prices .periods select").val()+'/'+$(this).val()+'/');
		}
	});
});

// !!!!!!!!!!!!!!!!!!
// Ext.EventManager.on(document, 'click', function(e, t) {
// 	if(e.getTarget('#countries') == null && Ext.get('countries_list').isVisible()) {
// 		Ext.get('countries_list').hide(true);
// 	}
// });
