$(document).ready(function() {
	$(".searchinput").attr('autocomplete', 'off');
	$("#from").focus();
	$(".searchinput").keyup(function() {
		if(this.value != '') {
			$(".bgtext").hide();
		}
	});
	$(".searchinput").autocomplete(names,{	
		width: 210,
		selectFirst: false,
		max: 15,
		scroll: false,
		matchContains: true
	});

	$('#searchform').submit(
		function(){
			$('#loader').css({visibility: "visible"});
			$('#page').hide();
			$.post('search.php', $("#searchform").serialize(), 
									function(response, status, xhr) {
										if(status == "error") {
											var msg = "Przepraszamy ale wystąpił błąd:<br>";
											$("#page").html(msg + xhr.status + " " + xhr.statusText);
										}
										else
										{
											$('#page').html(response);
										}
										$('#page').show();
										$('#loader').css({visibility: "hidden"});
										$().detailsButton();
			});
			$('.active').removeClass('active');
			return false;
		}
	);
	
	jQuery.fn.detailsButton = function() {
		$('.details').hide();
		$('.details_button').css({visibility: "visible"});
		$('.details_button').click(function() {
			if($(this).children().attr('src') == 'images/more.png')
			{
				var details = $(this).parent().children('.details');
				var image = $(this).children();
				if(details.html() != '')
				{
					details.slideDown('slow', function() {
						$(this).show();
					});
					image.attr('src','images/less.png');
					return;
				}
				image.attr('src','images/small_loader.gif');
				var data = $(this).attr('data').split(';');
				$.post('details.php', {k: data[0], w: data[1], f: data[2], t: data[3]}, 
										function(response, status, xhr) {
											if(status == "error") {
												var msg = "Przepraszamy ale wystąpił błąd:<br>";
												details.html(msg + xhr.status + " " + xhr.statusText);
											}
											else
											{
												details.html(response);
											}
											details.css({width: '500px'});
											details.slideDown('slow', function() {
												$(this).show();
											});
											image.attr('src','images/less.png');
				});
			}
			else
			{
				$(this).parent().children('.details').slideUp('slow');
				$(this).children().attr('src','images/more.png');
			}
		});
	};
	
	$('a').click(function() {
		$('#loader').css({visibility: "visible"});
		var file = $(this).attr('href').split('?')[1];
		$('#page').load(file + '.php',
									function(response, status, xhr) {
										if(status == "error") {
											var msg = "Przepraszamy ale wystąpił błąd:<br>";
											$("#page").html(msg + xhr.status + " " + xhr.statusText);
										}
										$('#loader').css({visibility: "hidden"});
		});
		$('.active').removeClass('active');
		$(this).parent().addClass('active');
		return false;
	});
});
