var animate = false;
var random_anim;

$().ready(function() {
	$('#vyplnit a').hover(
	function () {
		start_animation();
	},
	function () {
		stop_animation();
	}
	);

	//preload image
	$('#pencila').show(10, function() {$('#pencila').hide()});

	random_anim_init();
});

function random_anim_init() {
	var time = Math.round(Math.random() * 10000) + 10000;

	random_anim = setTimeout(random_anim_run, time);
}

function random_anim_run() {
	if (!animate) {
		start_animation();
		setTimeout(stop_animation, 2000);
	}

	random_anim_init();
}

function start_animation() {
	$('#pencil').hide();
	$('#pencila').show();
	animate = true;
	run_animation();
}

function stop_animation() {
	animate = false;
}

function run_animation() {
	var top = Math.round(Math.random() * 20 - 10);
	var left = Math.round(Math.random() * 20 - 10);

	$('#pencila').animate({
		top: top + 'px',
		left: left + 'px'
	}, 200, null, function () {
		if (animate) run_animation();
		else {
			$('#pencil').show();
			$('#pencila').hide();
		}
	});
}