

var BugsPool = {
	delay_min: 5,	// Минимальная задержка до появления жука, сек
	delay_max: 60,
	
	code: 0,

	my_nick: "",
	my_uid: 0,
	cur_nick: "SomeOne",
	cur_uid: 1,

	BugTypes: [
		{img: "1.gif", w: 152, h:151, dx: 20},
		{img: "2.gif", w: 152, h:151, dx: -20},
	],

	Bug: {
		div: null,
		image: "1.gif",
		x: 0,
		dx: 20,
		y: 50,
		w: 100,
		h: 100,
		max_x: 1000,
		speed: 100,
		timer: null,

		Create: function() {
			if(BugsPool.Bug.div != null) return false;

			var typ = Math.round(Math.random() * (BugsPool.BugTypes.length - 1));

			BugsPool.Bug.image = BugsPool.BugTypes[typ].img;
			BugsPool.Bug.w = BugsPool.BugTypes[typ].w;
			BugsPool.Bug.h = BugsPool.BugTypes[typ].h;
			BugsPool.Bug.dx = BugsPool.BugTypes[typ].dx;

			if(BugsPool.Bug.dx > 0) {
				BugsPool.Bug.x = 0 - BugsPool.Bug.w;
				BugsPool.Bug.max_x = $(window).width();
			} else {
				BugsPool.Bug.x = $(window).width() + 1;
				BugsPool.Bug.max_x = 0 - BugsPool.Bug.w;
			}

			BugsPool.Bug.y = Math.round(Math.random() * $(window).height());

			var css = "top:" + BugsPool.Bug.y +
				"px; left:" + BugsPool.Bug.x +
				"px; width:" + BugsPool.Bug.w +
				"px; height:" + BugsPool.Bug.h +
				"px; line-height:" + BugsPool.Bug.h +
				"px; background:url('/i/bugs/" + BugsPool.Bug.image + "');";
			var html = "<div id='Bug' style=\"" + css + "\">" +
				"<a href='/users/" + BugsPool.cur_nick + "'>" + BugsPool.cur_nick + "</a></div>";
			$("body").append(html);
			BugsPool.Bug.div = $("#Bug");
			BugsPool.Bug.div.click(BugsPool.Bug.Click);

			BugsPool.Bug.Move();

			return true;
		},

		Move: function() {
			BugsPool.Bug.x += BugsPool.Bug.dx;
			BugsPool.Bug.div.css("left", BugsPool.Bug.x);

			if((BugsPool.Bug.dx > 0 && BugsPool.Bug.x > BugsPool.Bug.max_x) ||
				(BugsPool.Bug.dx < 0 && BugsPool.Bug.x < BugsPool.Bug.max_x))
			{
				BugsPool.Bug.Die();
			} else {
				BugsPool.Bug.timer = setTimeout(BugsPool.Bug.Move, BugsPool.Bug.speed);
			}
		},

		Die: function() {
			this.Remove();
			
			// Здесь таймаут ставить рандомно
			var to = BugsPool.delay_min + Math.round(Math.random() * BugsPool.delay_max) * 1000;
			setTimeout(this.Create, to);
		},

		Click: function() {
			clearTimeout(BugsPool.Bug.timer);
			
			if(BugsPool.my_uid != 0) {
				BugsPool.cur_nick = BugsPool.my_nick;
				BugsPool.cur_uid = BugsPool.my_uid;

				var html = "<a href='/users/" + BugsPool.cur_nick + "'>" + BugsPool.cur_nick + "</a>";
				BugsPool.Bug.div.html(html);

				// Сообщаем серверу, что дефолтный ник изменился
				$.post("/ajax/bug_click/", {code: BugsPool.code}, function() {});
			}
			
			BugsPool.Bug.div.click(BugsPool.Bug.Remove);
		},
		
		Remove: function() {
			if(BugsPool.Bug.div != null) BugsPool.Bug.div.remove();
			BugsPool.Bug.div = null;
		}
	},

	Init: function() {
		// А жизненный цикл жука начинается с его смерти
		BugsPool.Bug.Die();
	}
};
