var itemWidth = 155;
var currentItem = 0;
var itemCount = 0;
var items = [];
var itemDirection = 0;
var scrollSpeed = 700;
var canScrollManually = true;
var interval = 5000;

function animateItem()
{
	canScrollManually = false;

	if(itemDirection == 0)
	{
		var current = items.get(currentItem);

		$("#scroller .container a").animate(
		{
			left: "-=" + (itemWidth)
		}, scrollSpeed, function()
		{
			$(this).css("zIndex", 100);

			if(this == current)
			{
				$(current).css("left", ((itemCount - 1) * itemWidth) + "px").css("zIndex", 200);

				currentItem++;
				if(currentItem >= itemCount)
				{
					currentItem = 0;
				}

				canScrollManually = true;
			}
		});
	}
	else
	{
		var next = (currentItem + itemCount - 1) % itemCount;
		var current = items.get(next);

		$(items.get(next)).css("left", (-1 * itemWidth) + "px").css("zIndex", 200);

		$("#scroller .container a").animate(
		{
			left: "+=" + (itemWidth)
		}, scrollSpeed, function()
		{
			$(this).css("zIndex", 100);

			if(this == current)
			{
				currentItem--;
				if(currentItem < 0)
				{
					currentItem = itemCount - 1;
				}

				canScrollManually = true;
			}
		});
	}
}

function nextItem()
{
	if(!canScrollManually)
	{
		return;
	}

	itemDirection = 0;
	animateItem();
}

function prevItem()
{
	if(!canScrollManually)
	{
		return;
	}

	itemDirection = 1;
	animateItem();
}

$(document).ready(function()
{
	if($("#scroller").size() > 0)
	{
		if($("#scroller .container a").size() >= 5)
		{
			itemCount = $("#scroller .container a").size();
			$("#scroller .container").css("width", (itemCount * itemWidth)+ "px");

			items = $("#scroller .container a");

			for(var i = 0; i < items.size(); i++)
			{
				var item = items.get(i);
				$(item).css("left", (i * itemWidth) + "px");
			}

			$("#scroller .prev").click(function()
			{
				prevItem();
				return false;
			});
			$("#scroller .next").click(function()
			{
				nextItem();
				return false;
			});

			setInterval("nextItem()", interval);
		}
		else
		{
			$("#scroller").addClass("simple");
		}
	}

	$(".image-container img").load(function()
	{
		var height = 170; //$(this).height();
		var top = parseInt((height - $(this).height()) / 2, 10);
		$(this).css("position", "relative");
		$(this).css("top", top + "px");
	});

	$("#categories ul li a.link").click(function(event)
	{
		event.preventDefault();

		var submenu = $(this).parent().find("ul");

		if(submenu.hasClass("visible2"))
		{
			submenu.removeClass("visible2").slideUp(500);
		}
		else
		{
			submenu.addClass("ignore");

			$("#categories ul li ul").each(function()
			{
				if(this == submenu.get(0))
				{
					$(this).addClass("visible2").slideDown(500);
				}
				else
				{
					$(this).removeClass("visible2").slideUp(500);
				}
			});
		}
	});
});
