
var menu_container_id = 'mainMenu';
var menu_selected_item_id = 'menu_selected';
var returnTimer, animationTimer;

function BindArguments(fn)
{
	var args = [];
	for (var n = 1; n < arguments.length; n++)
	args.push(arguments[n]);
	return function () { return fn.apply(this, args); };
}

function movebg(where, animation)
{	
	clearTimeout(returnTimer);
	clearTimeout(animationTimer);
	
	var what = document.getElementById('back');

	var whereW = where.offsetWidth;
	
	var tp = where.offsetLeft;
	var fp = what.offsetLeft;
	
	what.style.visibility="visible";
	
	if (animation)
	{
		var speed = Math.abs(fp-tp) / 10;
		speed = Math.round(speed);

		if ((Math.abs(fp-tp) - speed) > 1)
		{
			resize(what.id, whereW);
			what.style.display = "block";
			move(what, fp, tp, speed);
		}
	}
	else
	{
		resize(what.id, whereW);
		what.style.display = "block";
		what.style.left = tp+'px';
	}
}

function moveback(animation)
{
	var menu_selected = document.getElementById(menu_selected_item_id);

	if (menu_selected)
	{
		//returnTimer = setTimeout(BindArguments(movebg, menu_selected, animation), 0);
		movebg(menu_selected, animation);
	}
	else
	{
		var back = document.getElementById('back');
		back.style.visibility = 'hidden';
	}
}


function move(what, from_position, to_position, speed)
{
	if (Math.abs(from_position-to_position) >= speed)
	{
		if (from_position < to_position)
		{
			from_position+=speed;
		}
		else
		{
			from_position-=speed;
		}

		what.style.left = from_position+'px';

		animationTimer = setTimeout(BindArguments(move, what, from_position, to_position, speed), 5);
		//animationTimer = setTimeout('move(what,'+from_position+','+to_position+','+speed+')', 5);
	}
	else
	{
		what.style.left = to_position+'px';
	}
}

function pos(a)
{
	var k = document.getElementById(a);
	var apa = k.parentNode; // span
	if (k.childNodes.length == 0)
	{
		var nd = document.createElement('div');
		nd.className = 'back_sub_left';
		nd.style.width = (apa.offsetWidth/2) + 'px';
		k.appendChild(nd);
	}

	k.style.width = apa.offsetWidth + 'px';
		
	return true;
}

function resize(a, size)
{
	var k = document.getElementById(a);
		
	if (k.childNodes.length == 0)
	{
		var nd = document.createElement('div');
		nd.className = 'back_sub_left';
		k.appendChild(nd);
	}
			
	k.firstChild.style.width = Math.round(size/2) + 'px';
	k.style.width = size + 'px';
	
	return true;
}

function InitMainMenu()
{	
	var menu_container = document.getElementById(menu_container_id);
	
	if (menu_container)
	{
		var menu_links = menu_container.getElementsByTagName('a');
	
		for (var i=0; i<menu_links.length; ++i)
		{
			menu_links[i].onmouseover = BindArguments(movebg, menu_links[i], true);
			menu_links[i].onmouseout = function () { moveback(true) };
		}
	}
	
	moveback(false);
}

$(document).ready(InitMainMenu);
