$(document).ready(function () {
	function OffPage(Element) {
		var off = Element.offset();
		var t = off.top;
		var l = off.left;
		var h = Element.height();
		var w = Element.width();
		var docH = $(document).height();
		var docW = $(document).width();
		if (l + w > docW) { return true; } else { return false; }
	}
	var thisItem;
    function RootHoverOn(thisItem) {
    	//thisItem.children('.SubLevel').data('OrigHeight',$(this).height());
    	//thisItem.children('.SubLevel').data('OrigWidth',$(this).width());
		thisItem.addClass('Hover').find('.SubLevel')
			.stop()
			.css({'height':''})
			.slideDown(250);
    }
    function RootHoverOut(thisItem) {
    	//thisItem.children('.SubLevel').data('OrigHeight',$(this).height());
    	//thisItem.children('.SubLevel').data('OrigWidth',$(this).width());
		thisItem.removeClass('Hover').children('.SubLevel')
			.stop()
			.slideUp(500);
    }
    function SubHoverOver() { $(this).find('span').stop().animate({'paddingLeft':'10px'}); $(this).addClass('Hover'); }
    function SubHoverOut() { $(this).find('span').stop().animate({'paddingLeft':'0px'}); $(this).removeClass('Hover'); }
    $("#Nav .SubLevel .Item").hover(SubHoverOver, SubHoverOut);
    
	$('#Nav .Root').each(function(i){ $(this).addClass('Num'+i); });


	// Magic Line ----------------------------------------------------------------------------------------
	
    var $el, leftPos, newWidth, NewBG;
    
    /* Add Magic Line markup via JavaScript, because it ain't gonna work without */
    $("#Nav .TopLevel").append("<li id='MagicLine'></li>");
    
    /* Cache it */
    var $magicLine = $("#MagicLine");
    var $Selected =  $("#Nav .TopLevel > .Item.BC");
    if ($Selected.length>0) {
    	$magicLine.width($Selected.width()).css({'backgroundColor':$Selected.find('a').css('backgroundColor'),'left':$Selected.position().left+20})
    }
    $magicLine
        .data("origBGColor", $magicLine.css('backgroundColor'))
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width()
    );
    $("#Nav .Item.Root").hover(
    	function() {
			$el = $(this).find('a');
			NewBG = $el.css('backgroundColor');
			leftPos = $el.parent().position().left+20;
			newWidth = $el.width();
			
			$magicLine.stop().animate({
				backgroundColor: NewBG,
				left: leftPos,
				width: newWidth
			},500,
			function(){
				RootHoverOn($el.parent('li'));
			});
		},
		function() {
			$magicLine.stop().animate({
				backgroundColor: $magicLine.data("origBGColor"),
				left: $magicLine.data("origLeft"),
				width: $magicLine.data("origWidth")
			}, 500, RootHoverOut($(this)));   
		}
	);
});
