var isTrayVisible = false;
var mouseOver = false;

$(document).ready(function() {
	$('.menuitem:first').addClass('firstitem');
	$('.menuitem').bind('mouseover click', function(event) {
		mouseOver = true;
		if (!$(this).hasClass('menuhover')) {
			deselectAll();
			var links = getLinks($(this));
			var align = "center";
			if ($(this).hasClass('leftlinks')) {
				align = "left";
			} 
			if ($(this).hasClass('rightlinks')) {
				align = "right";
			}
			$(this).addClass('menuhover');
			if (!isTrayVisible && $('#linkstray').queue().length == 0) {
				setTrayLinks(links, align);
			//	$('#linkstray').css('opacity', 0.95)
				$('#linkstray').slideDown(200, function() {
					isTrayVisible = true;
				});
			} else {
				$('#linkstray').clearQueue();
				$('#linkstray').fadeOut(0, function() {
					setTrayLinks(links, align);
					$('#linkstray').slideDown(100);
				});
			}
		}
		event.stopPropagation();
	});
	$('body').bind('mouseover click', function(event) {
		//alert('');
		mouseOver = false;
		if (isTrayVisible) {
			isTrayVisible = false;
			$('#linkstray').delay(1000).slideUp(200, function() {
				deselectAll();
			});
		}
		event.stopPropagation();
	});
	$('#linkstray').bind('mouseover', function(event) {
		$(this).clearQueue();
		event.stopPropagation();
	});
	$(window).resize(function() {
		if (isTrayVisible) {
			$('#linkstray').css('left',$('.menuhover').position().left+'px');
		}
	});
});

function deselectAll() {
	$('.menuhover').each(function() {
		$(this).removeClass('menuhover');
	});
}

function getLinks(menuItem) {
	var returnString = "";
	var lastOne = menuItem.find('a').length;
	menuItem.find('a').each(function(index) {
		returnString += '<a href="' + $(this).attr('href') + '">' + $(this).html() + '</a>';
		if (index != (lastOne - 1)) {
			
		}
	});
	return returnString;
}

function setTrayLinks(content, align) {
	$('#linkstray').removeAttr( 'style' );
	$('#linkstray').css('opacity', 0.95)
	$('#linkstray').css('left',$('.menuhover').position().left+'px');
	$('#linkstray').css('width',$('.menuhover').width()+'px');
	$('#linkstray').find('#traycontent').html(content);
	//$('#linkstray').css('text-align', align);
}

function getMouseOver() {
	return mouseOver;
}
