$(function() {
	var routeUrl = '/to_passangers/routes/';
	var imgUrl = '/builder/'+ $('input.name_template').val()+ '/img/';	
	
	$("#type_transport").change(function() {
		var $this = $(this),
			val = $(this).val();
		if (val == 'trolley') {
			$("#num_route_trolley").show();
			$("#num_route_tram").hide();
		} else {
			$("#num_route_trolley").hide();
			$("#num_route_tram").show();
		}
	});
	$("#submit_route_to").click(function() {
		window.location = routeUrl+'?rid=' + $( "#num_route_" + $("#type_transport").val() ).val();
	});
	
	$("#stop_from, #stop_to").autocomplete({
		source: function( request, response ) {
			$.getJSON( routeUrl+"?x=1", request, function( data, status, xhr ) {
				response(
					$.map(data, function(text) {
						return {
							label: text.replace(
								new RegExp(
									"(?![^&;]+;)(?!<[^<>]*)(" +
									$.ui.autocomplete.escapeRegex(request.term) +
									")(?![^<>]*>)(?![^&;]+;)", "gi"
								), "\u003cstrong\u003e$1\u003c/strong\u003e" ),
							value: text,
							option: this
						};
					})
				);
			});
		},
		delay: 300,
		minLength: 2
	}).each(function() {
		$(this).data("autocomplete" )._renderItem = function( ul, item ) {
			return $( "\u003cli\u003e\u003c/li\u003e" )
				.data( "item.autocomplete", item )
				.append( "\u003ca\u003e" + item.label + "\u003c/a\u003e" )
				.appendTo( ul );
		};
	});
	
	var searchForRoute = function() {
		var stop_from = $("#stop_from").val(),
			stop_to = $("#stop_to").val();
		if (!stop_from || !stop_to) {
			alert("Введите названия остановок");
			return;
		}
		$.ajax({
				type: 'POST',
				url: routeUrl,
				data: {
					'x': 1,
					'search': 1,
					'stop_from': stop_from,
					'stop_to': stop_to
				},
				success: function( data, status, xhr ) {
					var str;
					if (data.length == 0) {
						str = '<h1>Прямого&nbsp;маршрута&nbsp;между&nbsp;остановками&nbsp;не&nbsp;найдено</h1>';
					} else {
						str = '<h1>Найденные&nbsp;маршруты</h1><ul>';
						for (var i=0;i<data.length;i++) {							
							str += '<li class="'+data[i].type+'">';
							str += '<a href="'+routeUrl+'?rid='+data[i].route_id+'"><img src='+imgUrl+(data[i].type == 'tram' ? 'tram_big.png ' : 'troll_big.png ')+'></a>';
							str += '<a class="text" href="'+routeUrl+'?rid='+data[i].route_id+'">';
							str += (data[i].type == 'tram' ? 'Трамвай ' : 'Троллейбус ') + data[i].name;
							str += '</a></li>';
						}
						str += '</ul>';
					}
					//alert(str);
					pop_block_str = '<div class="pop_shadow"></div>'+
									'<div class="border_shadow pop_block">'+
										'<div class="pop_content">'+
											'<div class="pop_close"></div>'+
											str+
										'</div>'+
									'</div>';
					
					if (!$('.pop_shadow').length){
						$('body').append(pop_block_str);
						
						 $('.pop_shadow, .pop_block .pop_close').click(function(){							
							// $('.pop_block').fadeOut(200,function(){
								//$('.pop_shadow').fadeOut(200);
							//});
							  $('.pop_block').animate({opacity:0},200,function(){
								 $(this).css('display','none');								
								  $('.pop_shadow').animate({opacity:0},200,function(){
									  $(this).css('display','none');
									  $('.pop_shadow').remove();
								  });
								  $('.pop_block').remove();
							   });						 
							 
						 })
						 
						$("#submit_stop_to").keypress(function(e) {
							if ((e.keyCode || e.which) == 27) {
								 $('.pop_block').fadeOut(200,function(){
									$('.pop_shadow').fadeOut(200);
								});	
							}
						});
						 
						 window.onscroll = function(){
						   $('.pop_shadow').css('height',$(document).height()+'px');
						   $('.pop_block').stop();
						   $('.pop_block').animate({top:Math.round($(window).height()/2 - $('.pop_block').height()/2  + $(document).scrollTop()), left:Math.round($(window).width()/2 - $('.pop_block').width()/2 + $(document).scrollLeft())},'20');
						  }
						  
						  $(window).resize(
							 function(){							
								 $('.pop_block').stop();
								 $('.pop_block').animate({top:Math.round($(window).height()/2 - $('.pop_block').height()/2  + $(document).scrollTop()), left:Math.round($(window).width()/2 - $('.pop_block').width()/2 + $(document).scrollLeft())},'20');
							}						
						  );
					  }					
					  
					  $('.pop_block').css('left',Math.round($(window).width()/2 - $('.pop_block').width()/2 +  + $(document).scrollLeft())+'px').css('top',Math.round($(window).height()/2 - $('.pop_block').height()/2 + $(document).scrollTop())+'px');
					   $('.pop_shadow').css('width',$(document).width()+'px').css('height',$(document).height()+'px');
					   
					   $('.pop_shadow').css('display','block').animate({opacity:0.6},200,function(){
						   $('.pop_block').css('display','block').animate({opacity:1},200);   
					   });					  
					
				},
				error: function( xhr, text, error) {
					alert('Произошла ошибка при запросе к серверу');
				},
				dataType: 'json'
			});
	}
	$("#stop_from").keydown(function(e) {
		if ((e.keyCode || e.which) == 13) {
			if ($(this).val()) {
				if ($("#stop_to").val()) {
					 searchForRoute();
				} else {
					$("#stop_to").focus();
				}
			}
		}
	});
	$("#stop_to").keydown(function(e) {
		if ((e.keyCode || e.which) == 13) {
			if ($(this).val()) {
				if ($("#stop_from").val()) {
					searchForRoute();
				} else {
					$("#stop_from").focus();
				}
			}
		}
	});
	$("#submit_stop_to").click(function(e) { searchForRoute() });
	$("#submit_stop_to").keydown(function(e) {
		if ((e.keyCode || e.which) == 13) { searchForRoute(); }
	});
});
