var DELAY = function(fn, args)
{
	var debug = false
	var me = this,
			 id,
	call = function()
	{
		if(debug) alert('call');
		clearInterval(id);
		id = null;
		fn(args);
	};

	me.isOn = function()
	{
		return id !== null;
	};

	me.pozje = function(delay, newFn, newArgs)
	{
		if(debug) alert('delay');
		me.otmena();
		fn = newFn || fn;
		args = newArgs || args;
		id = setInterval(call, delay);
	};

	me.seychas = function(newArgs)
	{
		me.otmena();
		args = newArgs || args;
		call();
	};

	me.otmena = function()
	{
		if(debug) alert('cancel');
		if(id)
		{
			clearInterval(id);
			id = null;
		}
	};
};

var active = {};

$(document).ready(function()
{
	$('.catalog a').mouseover(function()
	{
		var next = $(this).next();
		var index = $(this).index();
		if(next.length && next.get(0).tagName == 'DIV' && next.get(0).className == 'submenu')
		{
			var link = $(this);
			var offsets = $(this).position();

			var lvl = $(this).parents('.submenu').length;

			if(active[lvl] && active[lvl] !== this)
			{
				$(active[lvl]).next().hide();
				active[lvl] = false;
			}


			var dimens = {
				w: $(this).outerWidth(),
				h: $(this).outerHeight()
			};


			next.css({
				width: '207px',
				left: (offsets.left + dimens.w + 15 + (lvl*5)) + 'px'
			});
			if(!lvl) next.css({top: '-5px'});
			else next.css({top: offsets.top + 'px'});

			next.show();
			var close = new DELAY(function(args){
				args.next.hide();
				active[args.lvl] = active[args.lvl] === args.ind ? false : active[args.lvl];
				args.next.unbind();
				deactivate = [];
			}, {next: next, link: link, lvl: lvl, ind: index});


			link.parent().bind({
				mouseleave: (function(t){
					return function() {
						t.pozje(1000);
						link.removeClass('active');
					};
				})(close),
				mouseenter: (function(t){
					return function() {
						t.otmena();
						link.addClass('active');
					};
				})(close)
			});

			if(!active[lvl]) active[lvl] = false
			active[lvl] = this;
		}
	});

});


function var_dump(o)
{
	var r = '', i;
	for(i in o) r+= i + ': ' + o[i] + '\n';
	alert(r);
}
